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: <canvas> element requires the closing tag, like so:

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

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

<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:

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

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

<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.