rob_hicks
rob_hicks

Reputation: 1734

How to get correct height and width of Fabric.js object after modifying

After drawing an object and modifying the object with the mouse, the coordinates(Object.width and Object.height) remain the same as the originally drawn object.

const button = document.querySelector('button');

function load() {
  const canvas = new fabric.Canvas('c');
  const rect = new fabric.Rect({
    width: 100,
    height: 100,
    left: 10,
    top: 10,
    fill: 'yellow',
  });

  function objectAddedListener(ev) {
    let target = ev.target;
    console.log('left', target.left, 'top', target.top, 'width', target.width, 'height', target.height);
  }

  function objectMovedListener(ev) {
    let target = ev.target;
    console.log('left', target.left, 'top', target.top, 'width', target.width, 'height', target.height);
  }

  canvas.on('object:added', objectAddedListener);
  canvas.on('object:modified', objectMovedListener);

  canvas.add(rect);

}

load();

button.addEventListener('click', load);

See codepen

Upvotes: 3

Views: 6742

Answers (2)

redrom
redrom

Reputation: 11642

Currently You can use:

this.yourObject.getScaledWidth();
this.yourObject.getScaledHeight();

Which returns the same result.

Upvotes: 2

Durga
Durga

Reputation: 15604

width = target.width * target.scaleX, 
height = target.height * target.scaleY

As we are scalling, so you need to multiply the scaleX and scaleY value to width and height respectively. Here is updated codepen

Upvotes: 10

Related Questions