Skip to content

Instantly share code, notes, and snippets.

@unixpickle
Created April 5, 2018 22:32
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 unixpickle/5498faaf72909c4175144308998c6869 to your computer and use it in GitHub Desktop.
Save unixpickle/5498faaf72909c4175144308998c6869 to your computer and use it in GitHub Desktop.
Square particle explosion
<!doctype html>
<html>
<head>
<title>Wallpapers</title>
<style type="text/css">
body {
background-color: black;
margin: 0;
padding: 0;
}
canvas {
position: absolute;
left: 0;
top: 0;
}
</style>
<script type="text/javascript">
var NUM_PARTICLES = 1000;
function Particle() {
this.x = 0.25 + Math.random() * 0.5;
this.y = 0.25 + Math.random() * 0.5;
this.alpha = 1;
var angle = Math.random() * Math.PI * 2;
var radius = 0.3 * -Math.log(-Math.log(Math.random()));
this.dx = radius * Math.cos(angle);
this.dy = radius * Math.sin(angle);
this.color = randomColor();
}
Particle.prototype.step = function(dt) {
this.alpha = Math.max(0, this.alpha - 1 * dt);
this.x += this.dx * dt;
this.y += this.dy * dt;
};
function startAnimation() {
var canvas = document.getElementById('particles');
var particles = [];
for (var i = 0; i < NUM_PARTICLES; ++i) {
particles.push(new Particle());
}
var steps = 0;
var stepper;
stepper = function() {
for (var i = 0; i < particles.length; ++i) {
particles[i].step(1 / 190);
}
drawParticles(canvas, particles);
steps += 1;
if (steps < 190) {
setTimeout(stepper, 1000 / 24);
} else {
startAnimation();
}
};
stepper();
}
function drawParticles(canvas, particles) {
var ctx = canvas.getContext('2d');
var scale = Math.max(canvas.width, canvas.height);
var xOffset = (scale - canvas.width) / 2;
var yOffset = (scale - canvas.height) / 2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; ++i) {
var p = particles[i];
ctx.fillStyle = 'rgba(' + p.color + ', ' + p.alpha.toFixed(2) + ')';
ctx.fillRect(p.x * scale - xOffset, p.y * scale - yOffset, 3, 3);
}
}
function randomColor() {
var comps = [];
for (var i = 0; i < 3; ++i) {
comps.push(Math.floor(Math.random() * 255.9));
}
return comps.join(', ');
}
function handleResize() {
var canvas = document.getElementById('particles');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.onload = function() {
handleResize();
startAnimation();
};
window.onresize = handleResize;
</script>
</head>
<body>
<canvas id="particles" width="600" height="600"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment