Fabric.JS 如何避免中断 .animate 方法

How to avoid interruption of .animate method in Fabric.JS

在下面这个脚本中,红色方块会移动到点击点。

    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 回调转到事件查询

2) 当它触发红色方块时开始通过调用 canvas.requestRenderAll()

改变它的坐标

3)如果点击其他点,另一个回调(callback2)会转到事件队列。

触发速度相对较快,因此红色方块会从触发回调 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>

(出于测试目的,我放慢了动画速度)