Ad

How To Draw Canvas Using For Loop With Delay?

- 1 answer

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);
}

I have every x and y position move inside of 2D array (savedMove) and I want to draw with array information with delay. But Canvas does not draw this. I keep debugging but I cannot figure out the problem.

Ad

Answer

You're setting savedMove.length timers to tick parallelly every 100 milliseconds. I'm pretty sure this is not what you want, though it's hard to guess what it is. First I would change setInterval to setTimeout and make them fire at different times, 100 ms away from each other:

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

Note that this is not the best way to do it, but certainly better than the original code.

Then you can debug it, 'cause you might draw out of the visible canvas:

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);
}
Ad
source: stackoverflow.com
Ad