Step 8

Let's make a Ball object that bounces off the edges of canvas!

Create a new file model/Ball.js with the following content:

import Sprite from "./Sprite.js";

class Ball extends Sprite {
  constructor(x, y, width, height, color) {
    super(x, y, width, height, color);
  }
  
  bounce(canvasWidth, canvasHeight) {

  }
}

export default Ball;

Update the bouce method:

bounce(canvasWidth, canvasHeight) {
  if (this.x < 0) {
    // bounce off the left edge
  } else if (this.x > canvasWidth) {
    // bounce off the right edge
  }

  if (this.y < 0) {
    // bounce off the top edge
  } else if (this.y > canvasHeight) {
    // bounce off the bottom edge
  }
}

To bounce off the edges of the canvas, we need to change the speed vector of the object.

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

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

We need to store the speed of the ball and allow it to be changed. (I'm using the term speed in a loose sense.)

class Ball extends Sprite {
  constructor(x, y, width, height, color) {
    super(x, y, width, height, color);
    this.dx = 0;
    this.dy = 0;
  }

  updateSpeed(dx, dy) {
    this.dx = dx;
    this.dy = dy;
  }
  
  move(canvasWidth, canvasHeight) { /* overriding the move method */
    super.move(this.dx, this.dy);
    this.bounce(canvasWidth, canvasHeight);
  }

  // bounce method not shown to save space!
}

Open script.js and get rid off redBlock and blueSprite! Then, add a ball object:

import Ball from "./model/Ball.js";

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

const ball = new Ball(canvas.width / 2, canvas.height - 30, 10, 10, "#0095DD");

ball.updateSpeed(2, -2);

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ball.draw(ctx);
  ball.move(canvas.width, canvas.height);
}

setInterval(draw, 10);

Save your code again and try it in your browser.