Yogesh Chauhan's Blog

How to create bouncing balls using HTML canvas and JavaScript?

in HTML & JavaScript on May 2, 2021

HTML canvas is easy to use when creating some basic games. You can use it for different types of drawings for e.g. draw a linedraw a circle or even draw a text image.

Recently I was playing with canvas and wanted to make the bouncing balls effect using canvas and JavaScript Class. This was my goal.

HTML

Just one HTML canvas tag.


JavaScript

Just some basic code to get the canvas tag using ID. Also, setting the window’s border as the canvas borders using innerWidth and innerHeight methods. pos variable to set position of canvas and you can set the number of balls you want.

randomcolor function is just to get a random color and randomPos for setting the initial position of the balls randomly.

Here’s the code so far:


Creating a Class

Let’s create the JavaScript class to create number of objects later on. We’ll add a class with a constructor and creating and updating methods.

To draw the circle, we can use different HTML canvas methods.

Here’s a great tutorial on MDN to understand the bounce off the walls.

Creating an array

Now, let’s add an empty array and fill it with the number of balls specified in the numberOfBalls variable.


As, you can see the balls are printed on the canvas. We just need to create the animation.

Change the position of the balls

Using setInterval, we can call the update method for each ball in the array to update the position.

We need to use clearRect method to remove the older drawing from the canvas. What if you don’t? Try and see what happens.

Here’s the working demo and final code:


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
DROP DATABASE (remove a database) from PostgresPostgresSafe Practice to add Links to cross-origin destinationUI/UXHow to render Lists in React?ReactHow to show and hide an element on click in React?ReactWHERE Clause in PostgresPostgresHow to create HTML elements with ID and class using JavaScript?HTML