Last active
January 2, 2025 10:51
-
-
Save Garciat/c616da0f95ecb75a4fa9ce128569d806 to your computer and use it in GitHub Desktop.
Fireworks // Draws very simple random particle-based fireworks on the screen.
This file contains 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>Fireworks</title> | |
<style>html,body{margin:0;height:100%;}</style> | |
</head> | |
<body> | |
<script defer> | |
const SCRW = document.body.clientWidth; | |
const SCRH = document.body.clientHeight; | |
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'); | |
let 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() { | |
particles = particles.filter((p) => p.y <= SCRH); | |
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