Spance Spance - 3 months ago 23
Javascript Question

Javascript ball bouncing back and forth indefinitely

I'm writing a simple JS function that draws a ball in canvas and just bounces it back and forth between the left and right borders of the screen indefinitely. I currently have it starting on the left side and going right. How I have it currently, it goes to the right but then gets stuck on the right edge; it doesn't bounce back. Any tips?

var dx=4;
var dy=4;
var y=150;
var x=10;
function draw(){
context= myCanvas.getContext('2d');
context.clearRect(0,0,htmlCanvas.width,htmlCanvas.height);
context.beginPath();
context.fillStyle="#0000ff";
context.arc(x,y,50,0,Math.PI*2,true);
context.closePath();
context.fill();
if(x<htmlCanvas.width)
x+=dx
if(x>htmlCanvas.width)
x-=dx;
}
setInterval(draw,10);

Answer

Change this:

if(x<htmlCanvas.width)
    x+=dx
if(x>htmlCanvas.width)
    x-=dx;

to this:

// move the ball
x += dx;

if (x > htmlCanvas.width - 50) {
   // if we hit the right edge, get back in bounds
   x = htmlCanvas.width - 50;
   // and reverse direction
   dx *= -1;
} else if (x < 50) {
   // if we hit the left edge, get back in bounds
   x = 50;
   // and reverse direction
   dx *= -1;
}
Comments