Step 10
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, dx, dy) {
super(x, y, width, height, color, dx, dy);
}
bounce(canvasWidth, canvasHeight) {
// TODO Implement me!
}
}
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 trajectory 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;
}
}
Open the main.js
file and replace its content with the following code:
import "./style.css";
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",
2,
-2
);
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ball.draw(ctx);
ball.move();
ball.bounce(canvas.width, canvas.height);
window.requestAnimationFrame(draw);
}
draw();
Save your code and observer the changes in the browser.