I'm learning JavaScript and I would like to know how to create multiple animated circles in the same canvas.(我正在学习JavaScript,并且想知道如何在同一画布上创建多个动画圆。)
I've created this function so I don't have to repeat the code for all the different circles:(我已经创建了此函数,因此不必重复所有不同圈子的代码:)
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's not working correctly.(但是,它不能正常工作。) Only the second ball appears in the screen, and the first ball keeps blinking.(屏幕上仅出现第二个球,第一个球保持闪烁。)
I hope someone can help me.(我希望有一个人可以帮助我。) Thanks.(谢谢。)
ask by Jo?o Mira translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…