我的 Canvas 充本地图。用户可以点击 Canvas ,它会在 map ( Canvas )上绘制一个标记。坐标存储在数组中。
当用户单击播放按钮时, Canvas 会在其位置绘制第一个数组标记,一秒钟后绘制第二个标记,再一秒钟后绘制第三个标记,依此类推。
我怎样才能做到这一点?我试过使用 for 循环并调用 setTimeout 函数,该函数在循环中传递 i 的值,但循环变得很快,我无法理解它。
function timer() {
for (i=0; i<array.length; i++){
play(i);
}
}
function play(i) {
setTimeout(function() {
ctx.clearRect(0,0, c.width, c.height);
ctx.beginPath();
ctx.moveTo(array[i].x, array[i].y);
ctx.lineTo(array[i].x,array[i].y);
cursor(array[i].x,array[i].y);
}, 1000);
}
最佳答案
使用 requestAnimationFrame 并存储刻度值的差异,以便您仅在每一秒过去后才处理您的更改。
如果不能使用requestAnimationFrame,那么使用setTimeout(play, 1000) 1000秒后再次调用play函数。当然,只需在最后增加索引并在索引超出范围之前停止。
不要使用 setInterval,因为它会超出您之前的间隔操作。它不会等待前一段处理完成。
例如
<script>
var lastTick = 0;
var elapsed = 0;
var index = 0;
var array = [4, 5, 6, 7, 8, 9, 10];
function animationLoop(tick) {
var diff = tick - lastTick;
elapsed += diff;
if (elapsed > 1000) {
ctx.clearRect(0, 0, c.width, c.height);
ctx.beginPath();
ctx.moveTo(array[index].x, array[index].y);
ctx.lineTo(array[index].x, array[index].y);
cursor(array[index].x, array[index].y);
elapsed -= 1000;
index++;
}
if (index < array.length) {
lastTick = tick;
window.requestAnimationFrame(animationLoop);
}
}
window.requestAnimationFrame(animationLoop);
</script>
关于javascript - HTML5 Canvas 中的计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558928/