Skip to content

Instantly share code, notes, and snippets.

@kgjenkins
Last active December 5, 2020 20:16
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 kgjenkins/02ea5c0b9e000138c9bb471eaaf319e7 to your computer and use it in GitHub Desktop.
Save kgjenkins/02ea5c0b9e000138c9bb471eaaf319e7 to your computer and use it in GitHub Desktop.
Explosion followed by glitch art
<html>
<head>
</head>
<body>
<canvas id='canvas' width=960 height=500></canvas>
<script>
var c = canvas.getContext('2d');
// background
c.fillStyle = '#000';
c.fillRect(0,0,960,500);
var gravity = 0.05;
var dampening = 0.8;
var dangle = 1.05;
var mangle = 90;
var angle = mangle;
var force = 10;
var ox = 512;
var oy = 0;
function createBall() {
angle += dangle;
if (Math.abs(angle) > mangle) {
dangle = -dangle;
angle = angle + 2*dangle;
}
var f = rand(0,force) * rand(0.1, 1);
var radians = Math.PI/2 - angle/90*Math.PI/2;
return {
x:ox,
y:oy,
dx:Math.cos(radians)*f/2,
dy:Math.sin(radians)*f,
size:Math.floor(5 + rand(0,f))
}
}
var ball = createBall();
var balls = [];
for (var i=0; i<2000; i++) {
balls[i] = createBall();
}
function loop(timestamp) {
var elapsed = timestamp - c.lastRender;
for (var i=0; i<balls.length; i++) {
var ball = balls[i];
drawball(ball, erase=true);
ball.x += ball.dx;
ball.y += ball.dy;
if (ball.y < 0) {
ball.y = - ball.y;
ball.dy = - ball.dy * dampening;
}
ball.dy -= gravity;
gravity *= 1.000005;
if (ball.x>960 || ball.x<0 || (Math.abs(ball.dy)<0.1) && ball.y<10) {
drawball(ball, erase=true);
balls[i] = createBall();
}
else {
drawball(ball);
}
}
c.lastRender = timestamp;
window.requestAnimationFrame(loop);
}
c.lastRender = 0;
window.requestAnimationFrame(loop);
function drawball(ball, erase=false) {
c.fillStyle = erase ? '#000000' : (ball.color ? ball.color : '#ffffff');
c.fillRect(Math.round(ball.x), Math.round(500 - ball.y), ball.size, ball.size);
}
function rand(min, max) {
return Math.random() * (max - min) + min;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment