如何在修改后获得Fabric.js对象的正确高度和宽度

时间:2018-01-03 18:19:59

标签: fabricjs

绘制对象并使用鼠标修改对象后,坐标(Object.width和Object.height)保持与最初绘制的对象相同。

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);

请参阅codepen

1 个答案:

答案 0 :(得分:1)

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

由于我们是scalling,所以你需要将scaleX和scaleY值分别乘以width和height。此处已更新codepen