hellatan
hellatan

Reputation: 3577

Scaling image from the center (fabricjs)

I'm trying to scale an image using the centeredScaling: true option when setting up the Image instance. I have Circle object that is a "on" a slider that is supposed to be the scale.

Here's the example: http://jsfiddle.net/hellatan/tk1qs8ty/

A couple things: 1. it doesn't scale from the center 2. the starting point of the Circle object doesn't correlate correctly scaling the image properly (i'm guessing i'll have to adjust some math for this one, though)

Anyone have any clues as to what I'm doing wrong (mainly #1, #2 would be a bonus to know too).

Don't mind the sloppiness of the code =)

Upvotes: 5

Views: 11295

Answers (3)

BrunoLM
BrunoLM

Reputation: 100381

There's a hack I've seen around, basically it translates points to and from center in a wrapper for scaling/rotating.

Fiddle: http://jsfiddle.net/ywu45fpd/

Functions to translate points

fabric.Object.prototype.setOriginToCenter = function () {
    this._originalOriginX = this.originX;
    this._originalOriginY = this.originY;

    var center = this.getCenterPoint();

    this.set({
        originX: 'center',
        originY: 'center',
        left: center.x,
        top: center.y
    });
};

fabric.Object.prototype.setCenterToOrigin = function () {
    var originPoint = this.translateToOriginPoint(
    this.getCenterPoint(),
    this._originalOriginX,
    this._originalOriginY);

    this.set({
        originX: this._originalOriginX,
        originY: this._originalOriginY,
        left: originPoint.x,
        top: originPoint.y
    });
};

New method on canvas:

fabric.util.object.extend(fabric.Canvas.prototype, {

  _scale: function(e, target, value) {
    var scale = value,
        needsOriginRestore = false;

    if ((target.originX !== 'center' || target.originY !== 'center') && target.centeredRotation) {
      target.setOriginToCenter(target);
      needsOriginRestore = true;
    }

    target.animate({ scaleX: scale, scaleY: scale }, {
      onChange: canvas.renderAll.bind(canvas),
      easing: fabric.util.ease.easeOutQuad,
      onComplete: function() {
        if (needsOriginRestore) {
          target.setCenterToOrigin(target);
        }

        target.setCoords();

      },
    })

    canvas.renderAll();
  },

});

See mouse:up on fiddle for usage (basically canvas._scale(e, target, 2))

The same wrapper can be applied for rotating.

Upvotes: 1

ilgam
ilgam

Reputation: 4450

First step we are adding scale after calling the center of image. And then scale will be of center:

imgInstance.scale(my_value).center().setCoords()

Upvotes: -1

Ben Martin
Ben Martin

Reputation: 770

Try setting the origin for x and y to center, and adjust the initial x and y of the image

imgInstance.set({
        scaleY: imgH / origH,
        scaleX: imgW / origW,
        originX: "center", 
        originY: "center"
    });

Upvotes: 10

Related Questions