Learning to make a simple particle system using HTML5 Canvas and Javascript.
In this tutorial I will cover:
- Initialising Canvas
- Drawing circles
- Simple animation for particle movement using
SetInterval()
- 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
|
|
This creates a blank canvas for us to use. You can set the with and height at this point:
1
|
|
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
|
|
You can even include a different element inside the canvas element:
1
|
|
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.