2
I have a javascript code that makes an animation of a green ball that moves until it reaches the limit of the width of the window, causing the ball to return, do the opposite, until it reaches the other side of the window, and then come back again and so on.
var canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext("2d");
var x = 200;
var dx = 10;
var radius = 30;
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, window.innerWidth, window.innerHeight);
c.beginPath();
c.arc(x, 200, radius, 0, Math.PI * 2, false);
c.strokeStyle = "red";
c.fillStyle = "green";
c.stroke();
c.fill();
if (x + radius > window.innerWidth || x - radius < 0 ) {
dx = -dx;
}
x += dx;
};
animate();
My doubt is on that parole:
if (x + radius > window.innerWidth || x - radius < 0 ) {
dx = -dx;
}
The first time the ball reaches the window boundary, the first conditional is used, causing the value of the várivel dx
was negative, so the ball would start going backwards. Now when the ball reaches the other window boundary, the second conditional is used, running that code to leave the dx
negative.
My question is, why, when the second parole is used, the ball can come back again, and the value of the variable dx
It’s already negative, it wasn’t supposed to keep going on and on?