Creating an Animated Ball with Canvas HTML and JavaScript

·

4 min read

In this article, we will explore a snippet of code that allows you to create a simple animated ball using the Canvas HTML element and JavaScript. Let's dive in and understand how this code works.

First, we initialize variables for the ball's position (x and y), velocity (dx and dy), and size (w).

let x = 0,
  y = 0,
  dx = 3,
  dy = 3,
  w = 100;

Next, we begin by clearing the canvas using context.clearRect to avoid drawing multiple balls on each frame. We set the fill style to "#ddd" and begin a path with context.beginPath(). Using the context.ellipse method, we draw an ellipse representing the ball at the specified coordinates and size. Finally, we close the path with context.closePath() and fill the ellipse with context.fill().

context.clearRect(0, 0, fullWidth, fullHeight);
context.fillStyle = "#ddd";
context.beginPath();
context.ellipse(x + w, y + w, w, w, Math.PI / 4, 0, 2 * Math.PI);
context.closePath();
context.fill();

The code will render a static circle on screen. Now we define a function called animation that will handle the animation loop.

function animation() {
    //draw ellipse code ....
    context.clearRect(0, 0, fullWidth, fullHeight);
    context.fillStyle = "#ddd";
    context.beginPath();
    context.ellipse(x + w, y + w, w, w, Math.PI / 4, 0, 2 * Math.PI);
    context.closePath();
    context.fill();
    //animation code here
    //...
    //we call requestAnimationFrame(animation) to create a smooth animation loop that continuously updates the ball's position and redraws it on each frame.
    requestAnimationFrame(animation);
}
//call animation function
animation()

After drawing the ball, we update its position by adding the velocity (dx and dy) to its current coordinates.

x = x + dx;
y = y + dy;

Next, we check if the ball has reached the edges of the canvas. If so, we reverse the velocity by changing its sign, causing the ball to bounce off the boundaries.

if (x < 0 || x + 2* w > fullWidth) {
  dx = -dx;
}
if (y < 0 || y + 2* w > fullHeight) {
  dy = -dy;
}

By running this code, you will be able to see a ball moving within the boundaries of the canvas, bouncing off the edges. Feel free to customize the initial position, size, and velocity of the ball to create different animations using Canvas HTML and JavaScript.

Next, The above code is a simple way to create a moving ball. Next, we will explore a more advanced method using classes in JavaScript. The result will be similar to what we just created, but stay tuned to see a more flexible approach. Let's dive into the code and understand how it works.

class drawBall {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.dx = 3;
    this.dy = 3;
    this.w = 100;
  }

  draw() {
    context.clearRect(0, 0, fullWidth, fullHeight);
    context.fillStyle = "#ddd";
    context.beginPath();
    context.ellipse(
      this.x + this.w,
      this.y + this.w,
      this.w,
      this.w,
      Math.PI / 4,
      0,
      2 * Math.PI
    );
    context.closePath();
    context.stroke();
  }

  move() {
    this.x = this.x + this.dx;
    this.y = this.y + this.dy;
  }

  check() {
    if (this.x <= 0 || this.x + 2 * this.w > fullWidth) {
      this.dx = -this.dx;
    }
    if (this.y <= 0 || this.y + 2 * this.w > fullHeight) {
      this.dy = -this.dy;
    }
  }
}

The drawBall class has a constructor that takes the initial x and y coordinates of the ball as parameters. It also initializes the ball's velocity (dx and dy) and size (w).

The draw method is responsible for rendering the ball on the canvas. It starts by clearing the canvas using context.clearRect to avoid drawing multiple balls on each frame. It sets the fill style to "#ddd" and begins a new path with context.beginPath(). Using the context.ellipse method, it draws an ellipse representing the ball at the specified coordinates and size. Finally, it closes the path with context.closePath() and strokes the outline of the ellipse with context.stroke().

The move method updates the ball's position by adding the velocity (dx and dy) to its current coordinates.

The check method is used to detect if the ball has reached the edges of the canvas. If any of the conditions are met, it reverses the velocity by changing its sign, causing the ball to bounce off the boundaries.

It's quite similar to what we have created before, now let's find a way to execute it to produce the previous product.

let ball = new drawBall(0, 0)
let ball2 = new drawBall(10, 10)
const animation = () => {
  ball.draw();
  ball.move();
  ball.check();
  ball.draw()
  ball.move()
  ball.check()
  requestAnimationFrame(animation);
};
animation();

Let's show Ball showing on screen.

By utilizing the drawBall class and its methods, you can create and animate multiple balls on the canvas. You can control their movement, size, and behavior by interacting with the instance properties and methods of the class. We will continue with it in the next post to display multiple balls on a screen.