Skip to content

Instantly share code, notes, and snippets.

@poetix
Created December 25, 2011 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poetix/1519700 to your computer and use it in GitHub Desktop.
Save poetix/1519700 to your computer and use it in GitHub Desktop.
HTML5 canvas particle demo
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="scanva.js"></script>
<script src="particles.js"></script>
</head>
<body>
<canvas width="500px" height="500px" id="canvas"></canvas>
</body>
</html>
function newParticleModel() {
var particles = [];
function fade(ctx) {
ctx.fillStyle='rgba(0, 0, 0,0.1)';
ctx.fillRect(0, 0, 500, 500);
ctx.stroke();
}
function randomDelta() {
return (Math.random() * 12.0) - 6.0;
}
function randomRgbValue() {
return Math.floor(Math.random() * 256);
}
function randomColor() {
var rgba = [randomRgbValue(),
randomRgbValue(),
randomRgbValue()];
return {
paint: function(data, ptr) {
var i = 0;
for (i = 0; i < 3; i += 1) {
data[ptr] = rgba[i];
ptr += 1;
}
}
};
}
function newParticle() {
var x = 250,
y = 50,
dx = randomDelta(),
dy = randomDelta(),
colour = randomColor();
return {
draw: function(imageData) {
var pointIdx;
if (x < 0 || x > 500 || y < 0 || y > 500) {
return;
}
pointIdx = (Math.floor(x) << 2) + (Math.floor(y) * 2000);
colour.paint(imageData.data, pointIdx);
},
update: function() {
x += dx;
y += dy;
dy += 0.2;
}
};
}
function addParticles() {
var i;
for (i = 0; i < 10; i += 1) {
particles.push(newParticle());
}
}
function updateParticles() {
$.each(particles, function(i, particle) { particle.update(); });
}
function garbageCollect() {
while (particles.length > 500) {
particles.shift();
}
}
function draw(ctx) {
var imageData = ctx.getImageData(0, 0, 500, 500);
$.each(particles, function(i, particle) { particle.draw(imageData); });
ctx.putImageData(imageData, 0, 0);
}
function update() {
addParticles();
updateParticles();
garbageCollect();
}
function animatedOn(canvas) {
var withCanvas = scanva.withCanvas(canvas);
return function() {
withCanvas(fade, draw, update);
};
}
return {
animatedOn: animatedOn
};
}
$(document).ready(function() {
var canvas = document.getElementById("canvas"),
model = newParticleModel();
setInterval(model.animatedOn(canvas), 100);
});
var scanva = (function() {
function sequence(fs) {
return function(ctx) {
$.each(fs, function(i, f) {
f(ctx);
});
};
}
function inContext(ctx) {
return function() {
sequence(arguments)(ctx);
};
}
function withCanvas(canvas) {
var ctx = canvas.getContext("2d");
return inContext(ctx);
}
function restoring() {
var fs = arguments;
return function(ctx) {
ctx.save();
sequence(fs)(ctx);
ctx.restore();
};
}
return {
inContext: inContext,
withCanvas: withCanvas,
restoring: restoring
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment