Step 9

Let's refactor tune Ball.bounce:

bounce(canvasWidth, canvasHeight) {
  if (this.x < 0 || this.x > canvasWidth) {
    // bounce off the left/right edges
    this.dx *= -1; // switch direction
  } 

  if (this.y < 0 || this.y > canvasHeight) {
    // bounce off the top/bottom edge
    this.dy *= -1; // switch direction
  } 
}

Notice when the ball hits each edge it sinks into it slightly before changing direction. This is because we're calculating the collision point of the edge and the top left corner of the ball (Sprite). So, let's refactor!

bounce(canvasWidth, canvasHeight) {
  if (this.x < 0 || this.x + this.width > canvasWidth) {
    // bounce off the left/right edges
    this.dx *= -1; // switch direction
  } 

  if (this.y < 0 || this.y + this.height > canvasHeight) {
    // bounce off the top/bottom edge
    this.dy *= -1; // switch direction
  } 
}

Save your code again and try it in your browser.