Bouncing Balls in the HTML5 Canvas

Semi-transparent balls bouncing within a dark gray container.

Here’s a fun demo I put together using the HTML5 canvas, aided by the excellent sketch.js framework. I’m creating hundreds of semi-transparent balls and bouncing them around on the screen. The demo definitely requires a modern browser (Chrome/Firefox/IE9+).

See the Pen Bouncing Balls in sketch.js by Rob Glazebrook (@rglazebrook) on CodePen.

Join us in our newest publication:

Sketch.js simplifies getting started building demos like this by providing a bunch of things that would normally have to be built by hand: an animation loop, drawing context, and so on. It also provides a few nice math-y functions, like random(), which you’ll see I’m using all over the place.

I’ll walk through the code briefly to give you an idea of how it works, and how you can edit this one or make your own. You can follow along in the JS tab above.

First, I’m setting a few variables: a particles array, particleCount, and a Particle function. The particles array will hold every particle I create, while particleCount is the number of particles I’m going to create. Particle is a function which acts as my default for every particle I create. When I create a new particle, I pass it the x and y coordinates I want it to appear at. The rest is set internally: radius, color (in rgba), and velocity in both directions (vx and vy).

I also give Particle a couple of internal functions: update and draw. The update function updates that particle’s x/y coordinates. If it hits the edge of the screen, it reverses direction. The draw function draws the particle to the screen in its new location.

The sketch function has three internal functions: setup, update and draw.

Setup gets called automatically when the page loads. It loops through particleCount number of times and creates a new particle.

Update runs automatically each frame. It loops through the particles and runs each of their internal update functions (which in turn updates that particle’s position).

Draw is called automatically by sketch.js after update. It loops through the particles and calls their draw function (which draws the particle to the screen).

And that’s all we need! Sketch.js handles the rest of the dirty work.

Edit the demo on CodePen to see what changes you can make. Fun things to change include:

  • particleCount: increase/decrease the number of particles.
  • this.radius: changing the numbers inside the random function will change the size of particles created.
  • this.rgba: changing the numbers inside the four random functions within will change the colors created.
  • this.vx and this.vy: changing those numbers changes the velocities that the particles can have.

If you create something interesting, be sure to share it in the comments!

Share and Enjoy !

0 0