Skip to content

Instantly share code, notes, and snippets.

@itsbrex
Created March 30, 2023 07:15
Show Gist options
  • Save itsbrex/2435efe68b3237bc1af4252bef8b89d9 to your computer and use it in GitHub Desktop.
Save itsbrex/2435efe68b3237bc1af4252bef8b89d9 to your computer and use it in GitHub Desktop.
Trippy Particles
<canvas id="canvas"></canvas>
console.clear();
function Particle(x, y, offset = 50) {
let initY = y;
let initX = x;
const delayMultiplier = 10;
function draw(ctx) {
ctx.beginPath();
ctx.arc(Math.round(x), Math.round(y), 2, 0, 2*Math.PI);
ctx.fillStyle = '#fff';
ctx.fill();
}
function update(step, target) {
let hAngle = Math.atan2(initX - target[0], initY - target[1]); // deg
let xOffset = Math.sin(hAngle) * offset;
let yOffset = Math.cos(hAngle) * offset;
let hypot = Math.sqrt((Math.abs(target[0] - initX) * 2) + (Math.abs(target[1] - initY) * 2));
step = step - (hypot * delayMultiplier);
y = initY + (Math.sin(step * Math.PI / 180) * yOffset);
x = initX + (Math.sin(step * Math.PI / 180) * xOffset);
}
return {draw, update};
}
;(() => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let cw = canvas.width = canvas.offsetWidth;
let ch = canvas.height = canvas.offsetHeight;
let target = [cw / 2, ch / 2];
let xN = 50;
let yN = 25;
let gridItemWidth = (cw / xN);
let gridItemHeight = (ch / yN);
let particles = Array.from([...Array(xN * yN)]);
// lay the particles out in a grid
let iX = 0;
let iY = 0;
particles = particles.map(createParticle);
function createParticle(item) {
if(gridItemWidth * iX < cw) {
iX++;
} else {
iX = 0;
iY++;
}
return Particle(gridItemWidth * iX, gridItemHeight * iY);
}
function loop(t) {
let angle = Math.round(t / 10); // deg
ctx.beginPath();
ctx.rect(0,0,cw,ch);
ctx.fillStyle = 'rgba(0,0,0,.1)';
ctx.fill();
particles.forEach(particle => updateParticle(particle, angle));
requestAnimationFrame(loop);
}
function updateParticle(particle, angle){
particle.draw(ctx);
particle.update(angle, target);
}
document.body.addEventListener('mousemove', e => {
target = [e.clientX, e.clientY];
})
loop(0);
})();
body, html, canvas {
display: block;
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
body {
background-color: #000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment