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

问题描述 投票:1回答:1

绘制对象并使用鼠标修改对象后,坐标(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

fabricjs
1个回答
1
投票
width = target.width * target.scaleX, 
height = target.height * target.scaleY

因为我们是scalling,所以你需要将scaleX和scaleY值分别乘以width和height。这是更新的codepen

© www.soinside.com 2019 - 2024. All rights reserved.