Particle Fountain
HTML
<canvas id="particleCanvas" width="600" height="400"></canvas>
CSS
html, body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
JavaScript
// constants
var NUM_PARTICLES = 10;
var FPS = 60;
// global variables
var particles = [];
var mx = 20;
var my = 20;
var dmx = 1;
var dmy = -2;
var IE = document.all ? true : false;
//get a reference to the canvas
var canvas = document.getElementById("particleCanvas");
var ctx = canvas.getContext("2d");
function Particle () {
this.x = mx;
this.y = my;
this.s = 0.0;
this.dx = dmx + (Math.random() * 2) - 1;
this.dy = dmy + (Math.random() * 2) - 1;
this.ds = Math.random() + 0.1;
this.ttl = 4000; // particle lifetime
}
function onMouseMove(e) {
NUM_PARTICLES = 50;
var nmx, nmy;
if (IE) { // grab the x-y pos.s if browser is IE
nmx = event.clientX + document.body.scrollLeft;
nmy = event.clientY + document.body.scrollTop;
} else { // grab the x-y pos.s if browser is NS
nmx = e.pageX;
nmy = e.pageY;
}
dmx = (nmx - mx) / 8;
dmy = (nmy - my) / 8;
mx = nmx;
my = nmy;
}
function onTouch(e) {
NUM_PARTICLES = 150;
e.preventDefault();
var nmx, nmy;
nmx = e.pageX;
nmy = e.pageY;
dmx = (nmx - mx) / 50;
dmy = (nmy - my) / 50;
mx = nmx;
my = nmy;
}
function onRelease(e) {
NUM_PARTICLES = 0;
}
function updateParticle(p) {
//draw a circle
ctx.beginPath();
ctx.arc(p.x, p.y, p.s, 0, Math.PI * 2, true);
ctx.closePath();
ctx.stroke();
}
function createParticle() {
var p = new Particle();
updateParticle(p);
return p;
}
function updateParticles() {
canvas.width = document.body.offsetWidth;
canvas.height = document.body.offsetHeight;
//ctx.clearRect(0, 0, 600, 400);// very cool without this, and using fill
for (var i = 0; i < particles.length; i++) {
var particle = particles[i];
if (particle.x <= 0) particle.dx *= -1;
if (particle.y <= 0) particle.dy *= -1;
if (particle.x >= document.body.offsetWidth - 5) particle.dx *= -1;
if (particle.y >=...