Поскольку вы начинаете с canvas, я рекомендую вам использовать классы. Go через комментарии, чтобы вы все поняли, и сами опробовали новые вещи.
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
const squares = []; // make an array where squares will be stored
function Square(h, w, x, y, speed) {
// this.h is referencing to a single square's height
// h is the passed argument
// it goes like this for all of the properties a single square needs
// classes like this always require this type of defining
this.h = h;
this.w = w;
this.x = x;
this.y = y;
this.speed = speed;
this.draw = function() {
ctx.fillStyle = "#ff0000"
ctx.beginPath();
ctx.fillRect(this.x, this.y, this.w, this.h)
ctx.fill();
};
this.animate = function() {
this.y += this.speed; // movement
if (this.y > cvs.height) { // restart on top if the square fell entirely down
this.y = -cvs.height;
}
this.draw(); // draw a square after the "movement" changed it's position
};
}
for (let i = 0; i < 5; i++) {
let h = 20;
let w = 20;
let x = Math.floor(Math.random() * cvs.width); // random position from the available canvas width
let y = 0;
let speed = 5;
// now pass all of those made arguments
squares.push(new Square(h, w, x, y, speed)); // push these values to the array of squares TROUGH the class
}
function Update() {
ctx.clearRect(0, 0, cvs.width, cvs.height); // clear the canvas before drawing new squares
for (let i = 0; i < squares.length; i++) {
squares[i].animate(); // animate every square in the array of squares
}
requestAnimationFrame(Update); // recursive animation function
}
Update(); // start animating
function Square(h, w, x, y, speed) {...}
- это класс