Skip to content

Instantly share code, notes, and snippets.

@Garciat
Created January 1, 2018 13:11
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 Garciat/c616da0f95ecb75a4fa9ce128569d806 to your computer and use it in GitHub Desktop.
Save Garciat/c616da0f95ecb75a4fa9ce128569d806 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Fireworks</title>
</head>
<body>
<script>
const SCRW = 800;
const SCRH = 800;
const TAU = 2 * Math.PI;
const canvas = document.createElement('canvas');
canvas.width = SCRW;
canvas.height = SCRH;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const particles = [];
class Particle {
constructor(color, x, y, dx, dy) {
this.color = color;
this.x = x;
this.y = y;
this.dx = dx || 0;
this.dy = dy || 0;
}
}
function frand(a, b) {
return a + (b - a) * Math.random();
}
function irand(a, b) {
return a + Math.floor((b - a) * Math.random());
}
function firework(x, y) {
const n = irand(100, 120);
const color = `hsla(${frand(0, 360)}, 50%, 50%, 1)`;
for (var i = 0; i < n; ++i) {
const a = frand(0, TAU);
const v = frand(1, 10);
particles.push(new Particle(
color,
x, y,
v * Math.cos(a),
v * Math.sin(a)
));
}
}
function simulate() {
for (let particle of particles) {
particle.x += particle.dx;
particle.y += particle.dy;
particle.dy += 0.5;
}
}
function draw() {
for (let particle of particles) {
ctx.fillStyle = particle.color;
ctx.fillRect(particle.x, particle.y, 2, 2);
}
}
function clean() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, SCRW, SCRH);
}
var tick = 0;
function loop(n) {
clean();
simulate();
draw();
requestAnimationFrame(loop);
if (tick % 20 == 0) {
firework(irand(0, SCRW), irand(0, SCRH));
}
tick += 1;
}
requestAnimationFrame(loop);
// setTimeout(() => window.location.reload(), 5000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment