Lately, I've been experimenting with canvas and have encountered a challenge that I can't seem to solve. I've mastered creating shapes, animating them, and looping them across the canvas. However, I'm struggling to figure out how to spawn another shape behind the first one after a specific amount of time. My goal is to create a grid of squares moving horizontally.
I thought about encapsulating the for loop along with the shape's code in a variable and then using setTimeout()
to respawn the entire sequence after a set number of milliseconds, but I'm uncertain if that approach would be effective.
function draw(x,y) {
// Get canvas element
var canvas = document.getElementById('canvas');
// Set up drawing context
var ctx = canvas.getContext('2d');
// Begin drawing
ctx.save();
ctx.clearRect(0, 0, 550, 400);
for(var i = 0 ; i < 400 ; i+=10){
ctx.fillStyle = "rgb(0, 200, 0)";
ctx.fillRect(x, i, 5, 4);
}
ctx.restore();
x += 0.3;
var loopTimer = setTimeout('draw('+x+', '+y+')', 0.1);
}
draw(0,0);
canvas {
margin-left: 200px;
width: 550px;
height: 400px;
border: 1px solid #111111;
}
<canvas id="canvas"></canvas>