Linked particles
Description
Animated particles which connect to their neighbours and bounce of the walls. Click or tap to add a particle.
Created on 26 Oct 2026.
Code
<style>
canvas {
position: fixed;
inset: 0;
width: 100%;
}
</style>
<canvas></canvas>
<script type='module'>
const canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d');
const dpr = () => window.devicePixelRatio;
const particles = Array(Math.floor(20)).fill(null).map(() => ({
x: Math.random() * window.innerWidth * dpr(),
y: Math.random() * window.innerHeight * dpr(),
xStep: Math.random() * 2 - 1,
yStep: Math.random() * 2 - 1,
}));
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const particle of particles) {
for (const otherParticle of particles) {
const distance = Math.sqrt((particle.x - otherParticle.x) ** 2 + (particle.y - otherParticle.y) ** 2);
ctx.strokeStyle = `hsl(0 0 0 / ${100 - distance / 2}%)`;
ctx.lineWidth = dpr();
ctx.beginPath();
ctx.moveTo(particle.x, particle.y);
ctx.lineTo(otherParticle.x, otherParticle.y);
ctx.stroke();
}
ctx.beginPath();
ctx.ellipse(particle.x, particle.y, 4 * dpr(), 4 * dpr(), 0, 0, Math.PI * 2);
ctx.fill();
particle.x += particle.xStep;
particle.y += particle.yStep;
if (particle.x >= canvas.width || particle.x <= 0) {
particle.xStep = particle.xStep * -1;
}
if (particle.y >= canvas.height || particle.y <= 0) {
particle.yStep = particle.yStep * -1;
}
}
requestAnimationFrame(animate);
}
animate();
window.addEventListener('pointerdown', ({ x, y }) => particles.push({
x: x * dpr(),
y: y * dpr(),
xStep: Math.random() * 2 - 1,
yStep: Math.random() * 2 - 1,
}));
(window.onresize = () => {
canvas.width = window.innerWidth * window.devicePixelRatio;
canvas.height = window.innerHeight * window.devicePixelRatio;
})();
</script>