Search code examples
fabricjs

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


Solution

  • 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