const canvas = document.createElement('canvas');
const c = canvas.getContext('2d');
document.body.appendChild(canvas);
document.body.style.margin = 0;
function resize() {
canvas.width = innerWidth;
canvas.height = innerHeight;
c.fillStyle = '#000';
c.fillRect(0, 0, canvas.width, canvas.height);
}
resize();
addEventListener('resize', resize);
const cols = ['#555', 'white', 'gray', '#a4c3eb', '#75879e'];
const getCol = () => cols[Math.floor(Math.random() * cols.length)];
function rect() {
let x = innerWidth / 2;
let y = innerHeight / 2;
let col = getCol();
let width = 10;
let height = 10;
let halfWidth = width / 2;
let halfHeight = height / 2;
let alpha = 0.15 + Math.random() * 0.5;
let vx = 0;
let vy = 0;
let rot = 0;
let rotInc = Math.random() * 0.1 - 0.05;
function change() {
vx += (Math.random() * 1 - 0.5) / 2;
vy += (Math.random() * 1 - 0.2) / 2;
}
change();
function check() {
if (x < 0) x = innerWidth;
if (y < 0) y = innerHeight;
if (x > innerWidth) x = 0;
if (y > innerHeight) y = 0;
}
const radius = 20 + Math.random() * 80;
const verts = [];
const NUM = 200;
const off = Math.random() * 5;
const cols = [];
for (var i = 0; i < NUM; i += 2) {
let xp = Math.random() * 10 - 5;
let yp = Math.random() * 10 - 5;
let zp = Math.random() * 10 - 5;
let dist = Math.sqrt(xp * xp + yp * yp + zp * zp);
// normalize and scale x,y,z
verts[i] = (xp / dist) * radius;
verts[i + 1] = (yp / dist) * radius;
cols.push(i % 255);
}
return () => {
if (Math.random() < 0.13) {
change();
}
vx *= 0.99;
vy *= 0.99;
x += vx;
y += vy;
check();
c.globalAlpha = alpha;
c.save();
rot += rotInc;
c.translate(x, y);
c.rotate(rot);
for (var i = 0; i < NUM; i += 2) {
const channel = cols[i];
c.fillStyle = `rgb(${channel}, ${channel}, ${channel})`;
c.fillRect(verts[i], verts[i + 1], 2, 2);
}
c.restore();
};
}
let rects = [];
let NUM = 20;
for (let i = 0; i < NUM; i++) {
rects.push(rect());
}
rects[0]();
function loop() {
c.globalCompositeOperation = 'source-over';
c.globalAlpha = 0.025;
c.fillStyle = '#000';
c.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < NUM; i++) {
rects[i]();
}
requestAnimationFrame(loop);
}
loop();