在Fabric.js中出现形状的情况下,如何知道有人正在调整大小以使其变小还是变大

How to know whether someone is resizing to make it smaller or bigger in case of shapes in Fabric.js

本文关键字:调整 何知道 js Fabric 情况下      更新时间:2023-09-26

我正在开发Fabricjs库,希望在用户重新调整大小以使矩形(任何形状)变小或变大时进行验证。

意味着当用户调整大小以使其变小时,调用某个函数;当用户调整尺寸以增加大小时,调用另一个函数。

这在Fabricjs中可能吗?

您可以使用结构的canvas.on()方法来附加事件侦听器。

您要查找的是'object:scaling''object:resizing'
然后,您只需要查看对象的scaleXscaleYwidthheight属性,就可以知道它是在增加还是在减少。

var canvas = new fabric.Canvas('c');
// create a rectangle object
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 20,
  height: 20
});
// one listener for the scale event (could be resize)
function scaleListener(e) {
  // get the object being rescaled
  var targ = e.target;
  // check if we the scale was bigger than the new one
  if (targ.scaleX > (targ.lastScaleX || 1) || targ.scaleY > (targ.lastScaleY || 1)) {
    // it was
    bigger();
  } else {
    // it wasn't
    smaller();
  }
  // save the current scale as the last one in the object itself
  targ.lastScaleX = targ.scaleX;
  targ.lastScaleY = targ.scaleY;
};
function bigger() {
  rect.fill = 'blue';
}
function smaller() {
    rect.fill = 'green';
  }
  // "add" rectangle onto canvas
canvas.add(rect);
canvas.on({
  'object:scaling': scaleListener,
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.js"></script>
<canvas id="c"><</canvas>