javascript - 防止元素在 Canvas 中突然跳跃?

标签 javascript html canvas requestanimationframe

这是我的伪代码:

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/

相关文章:

html - 如何垂直对齐 div 或 span,并将它们向相反的方向 float ?

html - 如何对齐div中的文本

javascript - 编辑两个 Canvas 元素

javascript - HTML5 canvas渲染矩形的奇怪bug(?)

javascript - 如何为 HTML 助手 ASP.NET MVC 编写 Javascript 代码?

javascript - 谷歌地图V3绘制多边形并打开InfoWindow

html - 如何阻止我的移动菜单将我的网站向下移动?

Javascript 为什么当我在 `mousemove` 中使用 drawImage 时,我得到的图像很差?

javascript - 仅接受数字和 + 符号的 HTML 输入

javascript - 以 Angular 生成动态下拉列表