3
Hello,
I am learning Javascript and would like to know how to create several animated balls. I thought of creating this function so I didn’t have to repeat the code for all the balls:
const canvas = document.querySelector("canvas").getContext("2d");
balls = (color, x, y, dx, dy) => {
setInterval (() => {
canvas.clearRect(0, 0, 600, 600);
canvas.fillStyle = color;
canvas.beginPath();
canvas.arc(x, y, 20, 0, Math.PI * 2);
canvas.fill();
if (x >= 600 || x <= 0) {
dx = -dx;
}
if (y >= 600 || y <= 0) {
dy = -dy;
}
x = x + dx;
y = y + dy;
}, 20);
}
balls("#00f", 35, 35, 5, 5);
balls("#f00", 400, 35, 5, 5);
However it is not working properly as only the second ball appears on the screen, while the first one flashes at intervals.
What am I doing wrong? Can anyone help me? Thank you.