简体   繁体   English

防止元素在画布中突然跳跃?

[英]Preventing elements from jumping abruptly in canvas?

This is my pseudocode: 这是我的伪代码:

when move button is pressed:
    currentCirclePos = circleX;
    moveTimer = setInterval(move, 10);  

My move function looks like this: 我的移动功能如下所示:

var move = function() {
    circleX += move a bit;
};

In some cases, the element does not move at all. 在某些情况下,元素根本不会移动。 For those situations, I have the following code : 对于这些情况,我有以下代码:

while(Math.abs(circleX - currentCirclePos) < some distance away){
    drawCircle(circleX, circleY);
    circleX += gradual shift;
}

This does not change the position of my circle gradually but draws it abruptly some distance away . 这并没有逐渐改变我的圆圈的位置,而是突然间隔了some distance away I don't understand why is that happening. 我不明白为什么会这样。 Could anyone help me debug the issue? 任何人都可以帮我调试这个问题吗? Let me know if I need to post more code. 如果我需要发布更多代码,请告诉我。

This is my requestAnimationFrame code: 这是我的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);
}

UPDATE : The while loop was not inside the animation function but now it is. 更新:while循环不在动画函数内部,但现在是。 However, it did not make any difference at all. 但是,它根本没有任何区别。

The problem is that You're using setInterval instead of requestAnimationFrame - it's more reliable way to do this kind of operations on canvas. 问题是你使用setInterval而不是requestAnimationFrame - 这是在canvas上进行这种操作的更可靠的方法。

Please check this tutorial - author solves this problem pretty straightforward on example. 请查看本教程 - 作者在示例中非常简单地解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM