I have been messing around with canvas lately, and I came across a hurdle that I can't really overcome. I learned how to create shapes, animate them, and loop the same shape through the whole canvas (whether its x or y). It's hard to explain, but I cannot figure out how to spawn another shape behind the first one after a set amount of time. I want it to pretty much be a grid of squares moving horizontally.
I wanted to find some way to put that whole for loop with the code for the shape into a variable and then make a setTimeout()
to spawn the whole thing again after a certain amount of milliseconds, but I don't know if that would work.
function draw(x,y) { // Put canvas in variable var canvas = document.getElementById('canvas'); // Enable drawing var ctx = canvas.getContext('2d'); // Start 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>
You might want to create a square Class so you can create new objects on the fly.
function squareClass () {
//Position
this.X = 0;
this.Y = 0;
//Size
this.width = 5;
this.height = 4;
//Color to render
this.color = "rgb(0, 200, 0)";
//Move square
this.move = function() { this.X += 0.3; }
//Draw square
this.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.X, this.Y, this.width, this.height);
}
}
Now you can just use the square class to create all the squares you need.
var squareList = [];
function createASqaure() {
squareList.push(new squareClass());
}
Calling the createASquare class will produce new squares.
In order to use the functions inside of the squares you can simply loop through the squareList array and call the functions like so
function moveAndDraw() {
for (var i = 0; i < squareList.length; i++) {
squareList[i].move();
squareList[i].draw();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.