Skip to content

Instantly share code, notes, and snippets.

@nst
Last active November 24, 2024 14:06
Show Gist options
  • Save nst/f15776e81c16a72fe1d92b87440aed5a to your computer and use it in GitHub Desktop.
Save nst/f15776e81c16a72fe1d92b87440aed5a to your computer and use it in GitHub Desktop.
const canvas = document.getElementById('lines');
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
const G = 4, N = 6;
const rand = (max, step = 1) => Math.floor(Math.random() * max / step) * step;
const next = (line, vel) => line.map((p, i) => (vel[i] *= (p + vel[i] >= 0 && p + vel[i] < (i % 2 ? H : W)) ? 1 : -1, p + vel[i]));
const drawLines = (lines, ctx) => lines.forEach(l => ctx.stroke(new Path2D(`M ${l[0]} ${l[1]} L ${l[2]} ${l[3]}`)));
let V = Array.from({ length: G }, () => Array(4).fill(rand(18, 2) - 9));
let L = Array.from({ length: G }, () => Array(4).fill().map((_, i) => rand(i % 2 ? H : W)));
(async function animate() {
while (true) {
L = [...L.slice(0, G).map((l, i) => next(l, V[i])), ...L.slice(0, G * N)];
ctx.fillStyle = 'black'; ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = 'white';
drawLines(L, ctx);
await new Promise(r => setTimeout(r, 300));
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment