Draw particles using HTML5 Canvas

Raphael Amorim
4 min readJan 9, 2015

One thing is certain: canvas is the replacement for sudoku

Canvas for me has been the most fun technology in HTML5. The amount of cool things that can create only drawing geometric figures is very broad.

But many people think it’s too hard to learn. And it’s not.

Of course, know and have a good base geometry is very important. But if you do not know much, you can create simple things.

Let’s start coding!

In your HyperText Markup Langu… I mean: HTML file. Create a simple structure and add a canvas tag with a random class, in this example it shall be called "particles". And before the closing body tag, make the call the javascript file that will create called “particles.js”

<canvas class="particles"></canvas><script src="particles.js"></script></body>

Now in particles.js, let’s start the magic : )

I’ll explain some parts of the code. To get better understanding. This code is on GitHub (this link).

In the first part, a function was created to define the body and canvas, stylizing the basics. Note that I did not create any CSS file, I just applying the process startup.

window.onload = function() {
var body = document.querySelector(‘body’);
body.style.background = ‘#2C2C44';
canvas = document.getElementById(‘particles’),
ctx = canvas.getContext(‘2d’);
body.style.margin = ‘0px’;
canvas.style.margin = ‘0px’;
canvas.style.padding = ‘0px’;
canvas.width = canvas_width;
canvas.height = canvas_height;
draw = setInterval(update, speed);
}

I define some variables, such as speed of events and canvas size. Of course it’s not cool to be creating global variables, but I thought it would be more didactic.

In this project I am not using requestAnimationFrame but recommend taking a good look.

Why use requestAnimationFrame? "The browser can optimize concurrent animations together into a single reflow and repaint cycle, leading to higher fidelity animation. For example, JS-based animations synchronized with CSS transitions or SVG SMIL. Plus, if you’re running the animation loop in a tab that’s not visible, the browser will not keep it running, Which means less CPU, GPU, and memory usage, leading to much longer battery life".

Source of study for requestAnimationFrame: (this link)

// Settings
var speed = 35,
canvas_width = window.innerWidth,
canvas_height = window.innerHeight;

After that I created other global variables (never do that on your real project, is just to get better teaching) to set canvas instance, times that particles have been created, limit for particles, draw global function, array list of particles have been created and the colors used for generate randomic items.

var canvas,
ctx,
times = 0,
limit = 100,
draw,
particles = [],
colors = [‘#F0FD36', ‘#F49FF1', ‘#F53EAC’, ‘#76FBFA’];

If we are creating something that needs randomness in position, size and color of the particle. Why not use a function to deliver it. Not the best solution, but it is practical and easy to understand.

var getRand = function(type) {
if (type === ‘size’)
return (Math.floor(Math.random() * 8) * 10)
if (type === ‘color’)
return Math.floor(Math.random() * colors.length)
if (type === ‘pos’)
return [
(Math.floor(Math.random() * 200) * 10),
(Math.floor(Math.random() * 80) * 10)
]
return false
};

Okay, now let’s create a generic function to create particles from arguments. Pretty simple right?

var drawParticle = function(x, y, size, color, opacity){
ctx.beginPath();
ctx.globalAlpha = opacity;
ctx.arc(x, y, size, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
ctx.strokeStyle = color;
ctx.stroke();
}

Remember the update function? It is was put to run on setInterval within the function loaded on window.onload. It is the magic of drawing the particles and controlling the limit.

Realize that every particle designed, it also saves the particle list an object with information about it.

function update(args) {
var color = colors[getRand(‘color’)],
pos = getRand(‘pos’),
size = getRand(‘size’),
opacity = 1;
drawParticle(pos[0], pos[1], size, color, opacity) times++; particles.push([pos[0], pos[1], color, opacity, size]); if (times >= limit) {
clearInterval(draw);
draw = setInterval(clean, speed);
}
}

So far she only plays the particles on the screen, but still does not erase or start all over again.

To take care of this there is the clean function, which is executed when the particle limit is reached. This function reads each particle and updates its opacity, giving a visual effect of fadeOut.

function clean() {
ctx.clearRect(0, 0, canvas_width, canvas_height);
particles.forEach(function(p) {
/*
p[0] = x,
p[1] = y,
p[2] = color
p[3] = globalAlpha,
p[4] = size
*/
p[3] = p[3] — 0.06; drawParticle(p[0], p[1], p[4], p[2], p[3]) if (p[p.length — 1] && p[3] <= 0.0) {
ctx.clearRect(0, 0, canvas_width, canvas_height);
clearInterval(draw);
times = 0;
particles = []
draw = setInterval(update, speed);
}
});
}

Now if you run in your browser, you’ll see a nice canvas (you can see here too). This code needs refactoring, if you want you can send a PR on github. The idea was to show how simple it is to create canvas.

Have an different idea? give her a chance.

--

--