I love particle systems, so for part of a One Game a Month entry I decided to create one using HTML5 canvas and Javascript. This system creates little explosions of circles of various shades of a base colour.
You can view a fullscreen demo here, and the source is on Github.
<canvas id="canvas" width="900" height="500"></canvas>
<script src="js/Utility.js"></script>
<script src="js/Particle.js"></script>
<script src="js/ParticleSystem.js"></script>
// include the Utility, Particle and ParticleSystem files first
var particles = (function() {
var ctx;
var canvas;
var time;
function init() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var colour = '#52ef1d';
var particleSystem = new ParticleSystem(ctx);
// listen for click events and trigger particle explosion
canvas.addEventListener('mousedown', function(event) {
var mousePos = Utility.getMouseClick(canvas, event);
particleSystem.createExplosion(mousePos.x, mousePos.y, colour);
}, false);
// pick three random positions and create explosions there every 100ms
setInterval(function() {
for(var i = 0; i < 3; i++) {
var random = randomPos(canvas);
particleSystem.createExplosion(random.x, random.y, colour);
}
}, 100);
// request animation frame
(function animloop(){
requestAnimFrame(animloop);
var now = new Date().getTime();
var dt = now - (time || now);
time = now;
particleSystem.update(dt);
})();
}
// return a random co-ordinate in the canvas
function randomPos(canvas) {
return {
x: Math.floor(Math.random() * canvas.width),
y: Math.floor(Math.random() * canvas.height)
};
}
return {
init: init
};
})();
// wait til everything's loaded then start
$(document).ready(function() {
particles.init();
});