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 line, draw a circle or even draw a text image.
Just one HTML canvas tag.
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
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: