首页 > 解决方案 > 如何避免中断 Fabric.JS 中的 .animate 方法

问题描述

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

    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)去事件队列。

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

它是否正确 ?

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

谢谢 !

标签: javascriptcanvasfabricjs

解决方案


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>

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


推荐阅读