HTML5 Canvas Particles System (Pt. 1)

Learning to make a simple particle system using HTML5 Canvas and Javascript.

In this tutorial I will cover:

  1. Initialising Canvas
  2. Drawing circles
  3. Simple animation for particle movement using SetInterval()
  4. Improving the code using RequestAnimationFrame()

Initialising Canvas

Introduced in HTML5, the HTML <canvas> element can be used to draw graphics via scripting in JavaScript. The <canvas> element isn’t supported in some older browsers, but is supported in recent versions of all major browsers. More information can be found here: http://caniuse.com/#feat=canvas. <canvas> element requires the closing tag, like so:

1
<canvas id="myCanvas"></canvas>

This creates a blank canvas for us to use. You can set the with and height at this point:

1
<canvas id="myCanvas" width="500" height="300"> JavaScript Particles Canvas </canvas>

If not specified, width defaults to 300px and height defaults to 150px.

Some older versions of browsers do not support the <canvas> element, we can provide fallback content. We just provide alternate content inside the <canvas> element. Browsers which don’t support <canvas> will ignore the container and render the fallback content inside it, otherwise they will render the canvas normally:

1
<canvas id="myCanvas" width="500" height="300"></canvas>

You can even include a different element inside the canvas element:

1
<canvas id="myCanvas" width="500" height="300"><img src="img/example.png" width="500" height="300" alt="Example Image"></canvas>

We have now initialized a blank canvas and are ready to draw something. I will cover drawing circles in the next blog post.

🔥 If you enjoyed this post then you can keep up to date with my latests blogs posts & courses by following me on Twitter and checking out my code school for some hands on guided coding practice.