在下面的此脚本中,红色正方形将移动到单击的点。

    let canvas = new fabric.Canvas('canvas', {width: 500,height: 500});
    let square = new fabric.Rect({left: 100,top: 100,width: 50,height: 50,fill: 'red' });

    canvas.add(square);

    canvas.on('mouse:down', function (options) {
        let x = options.e.x;
        let y = options.e.y;
        square.animate ({ left: x, top: y }, {
            onChange: canvas.requestRenderAll.bind(canvas),
            duration: 500
        });
    })


但是,如果在正方形移动时单击另一个点,它将改变其在新点上的目的地
为什么会这样呢?

从我的角度来看,脚本流是这样的:

1)在按下鼠标事件时,.animate回调转到事件que

2)当它发射红场时,开始通过调用canvas.requestRenderAll()更改其坐标

3)如果单击其他位置,则另一个回调(callback2)进入事件que。

触发速度相对较快,因此红色方块会从回调2触发时的位置开始更改其目标

它是否正确 ?

我如何避免这种行为?我需要的是红色方块移动到第一点,并且没有新的单击会改变它的方式。只有当正方形完成移动时,我们才能选择新点,移动点

谢谢 !

最佳答案

在点击处理程序中,您可以在开始动画之前立即将其删除,然后将其重新附加到onComplete回调中:



const canvas = new fabric.Canvas('c');

let square = new fabric.Rect({left: 100,top: 100,width: 50,height: 50,fill: 'red' });

canvas.add(square);
const handler = function (options) {
  //remove handler
  this.off('mouse:down', handler);
  let x = options.e.x;
  let y = options.e.y;
  square.animate ({ left: x, top: y }, {
    onChange: canvas.requestRenderAll.bind(canvas),
    onComplete: () => {
      //reattach handler
      this.on('mouse:down', handler);
    },
    duration: 2000
  });
}
canvas.on('mouse:down', handler);

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script>
<canvas id='c' width="500" height="500"></canvas>





(出于测试目的,我将动画放慢了一点)

10-08 06:15