这是我的伪代码:
when move button is pressed:
currentCirclePos = circleX;
moveTimer = setInterval(move, 10);
我的移动函数如下所示:
var move = function() {
circleX += move a bit;
};
在某些情况下,元素根本不移动。对于这些情况,我有以下代码:
while(Math.abs(circleX - currentCirclePos) < some distance away){
drawCircle(circleX, circleY);
circleX += gradual shift;
}
这不会逐渐改变我的圆圈的位置,而是突然将其绘制一定距离
。我不明白为什么会发生这种情况。有人可以帮我调试这个问题吗?如果我需要发布更多代码,请告诉我。
这是我的requestAnimationFrame
代码:
requestAnimationFrame(animate);
function animate(){
ctx.clearRect(0,0,cw,ch);
ctx.rect(0, 0, cw, ch);
ctx.fillStyle = 'white';
ctx.fill();
drawCircle(circleX, circleY);
requestAnimationFrame(animate);
}
更新:while 循环原本不在动画函数内部,但现在是了。然而,这根本没有任何区别。
最佳答案
问题是您使用的是 setInterval
而不是 requestAnimationFrame - 这是在 Canvas 上执行此类操作的更可靠方法。
请查看this tutorial - 作者在示例中非常简单地解决了这个问题。
关于javascript - 防止元素在 Canvas 中突然跳跃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39331910/