如何使用延迟的 for 循环绘制画布

how to draw Canvas using for loop with delay?

本文关键字:绘制 循环 for 何使用 延迟      更新时间:2023-09-26
var context = document.getElementById("canvas").getContext("2d");
for(var i = 0; i< savedMove.length; i++){
    doSetTimeout(i);
}
function doSetTimeout(i) {
    setInterval(function() { animate(savedMove[i][0], savedMove[i][1]); }, 100);
}
function animate(xPos, yPos) {
    context.fillStyle = "red";
    context.fillRect(xPos, yPos, 5, 5);
}

我让每个 x 和 y 位置在 2D 数组 (savedMove) 内移动,我想延迟使用数组信息进行绘制。但 Canvas 没有画这个。我一直在调试,但我无法找出问题所在。

您将 savedMove.length 计时器设置为每 100 毫秒并行滴答一次。我很确定这不是你想要的,尽管很难猜测它是什么。首先,我将 setInterval 更改为 setTimeout,并使它们在不同的时间触发,彼此相距 100 毫秒:

function doSetTimeout(i) {
    setTimeout(function() { animate(savedMove[i][0], savedMove[i][1]); }, 100 * i);
}

请注意,这不是最好的方法,但肯定比原始代码更好。

然后你可以调试它,因为你可能会从可见的画布中绘制出来:

console.log("canvas size:", document.getElementById("canvas").width, document.getElementById("canvas").height);
function animate(xPos, yPos) {
    context.fillStyle = "red";
    context.fillRect(xPos, yPos, 5, 5);
    console.log("animate:", xPos, yPos);
}