javascript - 如何避免中断 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 触发时的位置开始更改其目的地
它是否正确 ?
我怎样才能避免这种行为?我需要的是红色方块移动到第一点并且没有新的点击会改变它的方式。只有当正方形完成它的移动时,我们才能选择新的点,它将移动到哪里
谢谢 !
解决方案
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>
(出于测试目的,我将动画放慢了一点)
推荐阅读
- c# - 如何在 Entity Framework 6 中创建字段并从连接表中获取数据
- python-3.x - 从 .csv 导入 Dataframe 导入为 OBJECT 而不是 FLOAT
- c++ - 返回值的 const 引用是什么?
- c - SELECTION SORT - 我自己的排序版本
- javascript - 自定义光标不工作 HTA(HTML 应用程序)
- uuid - 在 Rule Designer 工作区中同步新规则项目(重命名现有项目)时出现 UUID 问题
- sql - 5 列,但给出了 6 个值
- python - 如何在谷歌驱动器中使用制表符阅读 PDF 文件
- node.js - node.js - 错误:SQLITE_ERROR:靠近“用户”:语法错误
- r - 计算 MACD 和错误处理时,数字超出有效范围