Here, I will discuss random motion of particles inside a canvas and bouncing off the boundary. However, I will skip the collision between particles in this post which is a bit tricky and maybe I will do another post only on that topic.

Run the codepen to see the demo with code.

I have created an object called Circle and given it x and y coordinates and speed(sx,sy) in both directions with radius 5. The function drawCircle() uses arc shape function to draw a circle on canvas.

Next, to move the circle we need to change it’s x and y position. We do this by adding speed to current x and y position and then update the position, more the value of speed the faster the circle will move at each frame.

Now, we need to handle some conditions when the x-coordinate of circle is less then 0 or more than canvas width. If the circle’s x position is less than or equals 0, we change the x-coordinate to it’s radius and move it in the opposite direction by multiplying speed with -1. Again if the x-coordinate is more than the canvas width, the speed is changed as before but this time the x-coordinate is updated by subtracting the radius from width of canvas. We do the similar thing for y-coordinate.

The array circles[] stores position and speed of each circle. Both position and speed for any circle is random, which finally gives us the effect of particles moving randomly! The speed is a random value between 0.5 and 5. Finally, requestAnimationFrame runs the update() function and the canvas is cleared and drawn at each frame.

### Like this:

Like Loading...