const canvas = document.createElement('canvas'),
c = canvas.getContext('2d');
document.body.appendChild(canvas);
document.body.style.margin = 0;
function resize() {
canvas.width = innerWidth;
canvas.height = innerHeight;
c.fillStyle = '#ccc';
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 = Math.random() * innerWidth;
let y = Math.random() * innerHeight;
let dx = x;
let dy = y;
let size = Math.min(innerWidth, innerHeight);
let width = size * Math.random() * Math.random() + 30;
let height = size * Math.random() * Math.random() + 30;
let halfWidth = width / 2;
let halfHeight = height / 2;
let col = getCol();
let damp = 5 + Math.random() * 70;
let alpha = 0.2 + Math.random() * 0.4;
function move() {
if (Math.random() < 0.5) {
dy = y;
dx += Math.random() * Math.random() * size - size / 2;
} else {
dx = x;
dy += Math.random() * Math.random() * size - size / 2;
}
}
return () => {
if (Math.random() < 0.01) {
move();
}
if (x < halfWidth) {
dx = innerWidth - width;
}
if (y < halfHeight) {
dy = innerHeight - height;
}
if (x > innerWidth + halfWidth) {
dx = width;
}
if (y > innerHeight + halfHeight) {
dy = height;
}
x += (dx - x) / damp;
y += (dy - y) / damp;
c.globalAlpha = alpha;
c.fillStyle = col;
c.fillRect(x - halfWidth, y - halfHeight, width, height);
};
}
let rects = [];
let NUM = 30;
for (let i = 0; i < NUM; i++) {
rects.push(rect());
}
function loop() {
c.globalCompositeOperation = 'source-over';
c.globalAlpha = 0.01;
c.fillStyle = '#ccc';
c.fillRect(0, 0, canvas.width, canvas.height);
c.globalCompositeOperation = 'hard-light';
for (let i = 0; i < NUM; i++) {
rects[i]();
}
requestAnimationFrame(loop);
}
loop();