I'm drawing animated circles inside a canvas, and so far I managed to make it go from left to right inside the canvas. What I need to do is, when the circle reaches it's righmost position, to make it start its path (left to right) again, but in a position below. I'm trying to change it's y position by at least the circle's diameter, so far without success. Any insight on how can I achieve this? Is it better to make it part of the animation, or make the left-right movement a simple loop with a y position change at the end? My code so far is the following:
var canvas3 = document.getElementById("canvas3");
canvas3.width = 300;
canvas3.height = 500;
var c3 = canvas3.getContext("2d");
var radius = 13;
var x = radius;
var y = radius;
var dx = 1;
var dy = 0;
function animate3() {
requestAnimationFrame(animate3);
c3.clearRect(0, 0, 300, 500);
if (x radius > 300 || x - radius < 0) {
dx = 0;
y y;
}
if (y radius > 500 || y - radius < 0) {
dy = 0;
}
x = dx;
y = dy;
c3.beginPath();
c3.arc(x, y, 12, 0, Math.PI * 2, false);
c3.stroke();
c3.fillText(5, x - 3, y 3);
}
animate3();
CodePudding user response:
I would simply reset the x
position and increment the y
position like that :
var canvas3 = document.getElementById("canvas3");
canvas3.width = 300;
canvas3.height = 500;
var c3 = canvas3.getContext("2d");
var radius = 13;
var x = radius;
var y = radius;
var dx = 5;
var dy = 0;
function animate3() {
requestAnimationFrame(animate3);
c3.clearRect(0, 0, 300, 500);
if (x radius > 300 || x - radius < 0) {
x = radius;
y = radius;
}
if (y radius > 500 || y - radius < 0) {
y = radius;
}
x = dx;
y = dy;
c3.beginPath();
c3.arc(x, y, 12, 0, Math.PI * 2, false);
c3.stroke();
c3.fillText(5, x - 3, y 3);
}
animate3();
<canvas id="canvas3"/>