This post explains the steps required to draw circles and apply simple animations with collision detection.

Step 1 - Draw Circle

In this step, we will learn how to draw a circle in canvas using arc() method as explained below.

We have used beginPath() method to begin our path and called arc() method to add the circle operation. In the end, we have used stroke() method to draw all the accumulated operations. In our case, we have only added a single circle to the path.

The above code draws a Circle by considering x-axis from left to right and y-axis from top to bottom as shown below.

Step 2 - Draw multiple circles

In this step, we will draw multiple circles by using a simple iteration using for loop. We have also used Math.random() method to get a different value of x and y coordinate to randomize the position of circles.

Step 3 - Animate one circle

To animate the circle we have used requestAnimationFrame( functionName ) method. We have used dx and dy to control change in circle motion in x and y-direction respectively.

To move the circle, we are incrementing change in x and y value by 1. We have used dx and dy to control the animation speed of the Circle. If x and y values grow beyond 50 to 150 range, we have reversed the change by making dx and dy value negative and vice versa. The function clearRect() is used to clear the drawings made on Canvas in previous iterations.

The above-mentioned code adds an animated circle within the canvas boundaries as shown below:

Step 4 - Animate multiple circles

In order to draw and animate multiple circles, we have used circle class having draw and update function to preserve the location of each circle. The draw function is used to draw the circle and update function is used to control circle motion.

Similar to step 3, we will iterate and make multiple circles using circle class objects. We have used the function animate4() having for loop as our render or animation loop to iterate all circle objects and call the update method to change circle position.