Created
August 6, 2010 21:50
-
-
Save dansimpson/512068 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>JS1k, 1k demo submission</title> | |
<meta charset="utf-8" /> | |
</head> | |
<body> | |
<canvas id="c"></canvas> | |
<script> | |
(function render(canvas) { | |
var quantity = 1000; | |
var length = 6; | |
var colors = [{ | |
r: 0x66, | |
g: 0xcc, | |
b: 0xdd | |
},{ | |
r: 0x00, | |
g: 0x66, | |
b: 0xdd | |
},{ | |
}]; | |
var width = canvas.width = 1000; | |
var height = canvas.height = 600; | |
var ctx = canvas.getContext("2d"); | |
var img = ctx.createImageData(height, width); | |
var ticks = 0; | |
function buildParticle() { | |
var color = colors[Math.floor(Math.random() * colors.length)] | |
return { | |
t: [{ | |
x: Math.floor(Math.random() * width), | |
y: Math.floor(Math.random() * height) | |
}], | |
v: { | |
x: 1, | |
y: 1, | |
v: 1 | |
}, | |
r: color.r, | |
g: color.g, | |
b: color.b, | |
a: 255, | |
m: Math.round(Math.random() * 10), | |
move: function() { | |
this.t.unshift({ | |
x: this.t[0].x + (this.v.x * this.v.v), | |
y: this.t[0].y + (this.v.y * this.v.v) | |
}); | |
if(this.t.length > length) { | |
this.t.pop(); | |
} | |
} | |
}; | |
} | |
var particles = []; | |
for(var i = 0;i < quantity;i++) { | |
particles.push(buildParticle()); | |
} | |
function update() { | |
function shift(p) { | |
p.v.x = ((Math.random() * 1) > 0.5 ? 0 : 1) - Math.round(Math.random() * 1) | |
p.v.y = ((Math.random() * 1) > 0.5 ? 0 : 1) - Math.round(Math.random() * 1) | |
}; | |
var p, o, d = img.data; | |
for(var i = 0;i < quantity;i++) { | |
p = particles[i]; | |
o = (p.t[0].x + (height * p.t[0].y)) * 4; | |
d[o] = p.r | |
d[o + 1] = p.g | |
d[o + 2] = p.b | |
d[o + 3] = p.a | |
if(p.t.length > 1) { | |
for(var k = 1;k < p.t.length;k++) { | |
o = (p.t[k].x + (height * p.t[k].y)) * 4; | |
d[o + 3] = p.a - (255 / length) * k; | |
} | |
} | |
if(ticks % p.m == 0) { | |
shift(p); | |
} | |
p.move(); | |
} | |
++ticks; | |
ctx.putImageData(img, 0, 0); | |
} | |
setInterval(update, 50); | |
})(document.getElementById("c")); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment