[英]Animation while loop in HTML5 Canvas / Fabric js
编辑:为清楚起见,问题是为什么下面的代码不能按预期工作(为什么在while循环期间不进行动画处理),如何改进它以及如何在应该运行的单元中加红色通过用户输入滑块。
我的目标是使形状动画沿屏幕向下移动。 一个按钮将启动和停止动画。 还将输入变化速度或行进速度的输入。
我可以使其连续在屏幕上移动,但以下代码不起作用-我将ble用作测试变量,在最终方案中,我希望将其替换为while(stop != true)
或类似内容。
startDescent.onclick = function(){
startDescent.disabled = true; //prevent it being clicked again
//animation process
var ble = 1;
while(ble < 10){
console.log(ble);
testDrillbit.animate('top', '+=1',{
duration: 1000,
onChange: canvas.renderAll.bind(canvas),
onComplete: function(){
startDescent.disabled = false;
}
});
ble++;
}
};
+ = 1的增量也应该从用户输入框中读取,关于如何实现这一点的任何建议也将非常受欢迎。 感谢所有及任何帮助。
我相信您正在使用Fabric JS提供动画逻辑。 我的答案就是基于这个假设。
这个问题与您对动画功能如何工作的理解有关。 这不是同步呼叫。 因此,您的循环实际上将初始化动画动作10次,而不执行10个动画。 假设您定义的动作是在1秒钟的时间内将对象“ testDrillBit”下移1个像素,则看起来好像什么也没发生。
要估算您要执行的操作,您需要使用一个回调,该回调基本上指示动画何时完成,然后再次执行直到用户单击其“停止”按钮为止。 不过,这可能会导致动画变得生涩。 另外,您可以为动画设置任意大的端点并添加中止处理程序,但是随后您需要确定您的变化率(像素/时间)以得出正确的持续时间。
尚不清楚该库是否适合您的实现,但目前我无法提供替代方法。 下面的代码示例说明了第二个选项,同时说明了您要的要点,停止机制,变更率等。重要的变更不是将变更率指定为+ = 1,而是更改了所需的时间动画以完成较大距离的动画设置(在本例中为画布高度)。
首先,我们添加一个停止按钮和一个速度输入:
<button id="stop" disabled="true" onclick="stop=true;">Stop</button>
<form>
<input type="text" id="speed" value="10" />
</form>
然后,在脚本框中,确保可以使用这些值,然后在onclick处理程序中使用它们。
var stopBtn = document.getElementById('stop');
var speedBox = document.getElementById('speed');
var stop = false;
startDescent.onclick = function() {
// Get our speed, in case the user changes it. Speed here is actually the duration
// of the animation, not a true velocity. But, we can do something like entering 0.5
// and "slow down" the animation
var speed = 10000 / (new Number(speedBox.value));
stop = false; // ensure that we won't abort immediately
stopBtn.disabled = false; // enable the stop button
startDescent.disabled = true;
// I chose canvas.height as an arbitrary fixed distance. Not this won't stop the
// the element from rolling out of the canvas, its just a fixed value.
// The significant change is the addition of the "abort" function which basically
// polls our stop variable to determine whether the animation should be aborted.
testDrillbit.animate('top', "+="+canvas.height, {
duration: speed,
abort: function () {
// If the user has clicked the stop button, flip our buttons
if (stop) {
startDescent.disabled = false;
stopBtn.disabled = true;
}
return stop;
},
onChange: canvas.renderAll.bind(canvas),
onComplete: function() {
startDescent.disabled = false;
stopBtn.disabled = true;
}
});
};
上面的代码应允许用户通过延长或缩短执行动画的时间来更改“速度”。 另外,您还有机制可以在执行过程中停止动画。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.