Dynamic Colored Shapes
Home
Snippets
Dynamic Colored Shapes
HTML
CSS
JS
<div class="wrap" id="wrap"> <canvas id="c"></canvas> </div>
html, body { margin: 0; height: 100%; display: flex; justify-content: center; align-items: center; font-family: sans-serif; color: #eee; transition: background 1s ease; } .wrap { width: 90%; max-width: 900px; height: 90%; position: relative; border-radius: 12px; overflow: hidden; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6); transition: background 1s ease; } canvas { width: 100%; height: 100%; display: block; }
const canvas = document.getElementById("c"); const ctx = canvas.getContext("2d"); const wrap = document.getElementById("wrap"); let w, h, shapes = []; let hue = 270; let targetHue = 270; function resize() { const rect = canvas.getBoundingClientRect(); w = canvas.width = rect.width; h = canvas.height = rect.height; } function genShapes(hue, n = 40) { shapes = []; for (let i = 0; i < n; i++) { shapes.push({ x: Math.random() * w, y: Math.random() * h, dx: (Math.random() - 0.5) * 2, dy: (Math.random() - 0.5) * 2, r: 15 + Math.random() * 40, a: Math.random() * Math.PI * 2, da: (Math.random() - 0.5) * 0.05, type: Math.random() > 0.5 ? "circle" : "square", baseLight: 20 + Math.random() * 60, color: `hsl(${hue},80%,${20 + Math.random() * 60}%)` }); } } function updateColors(h) { const bodyGrad = `linear-gradient(180deg, hsl(${h},80%,15%), hsl(${h},80%,25%))`; document.body.style.background = bodyGrad; const overlayGray = Math.floor(0.25 * 255); wrap.style.background = `rgba(${overlayGray},${overlayGray},${overlayGray},0.25)`; } function draw() { ctx.clearRect(0, 0, w, h); shapes.forEach((s) => { s.x += s.dx; s.y += s.dy; s.a += s.da; if (s.x < 0 || s.x > w) s.dx *= -1; if (s.y < 0 || s.y > h) s.dy *= -1; ctx.save(); ctx.translate(s.x, s.y); ctx.rotate(s.a); ctx.fillStyle = s.color; if (s.type === "circle") { ctx.beginPath(); ctx.arc(0, 0, s.r, 0, Math.PI * 2); ctx.fill(); } else { ctx.fillRect(-s.r, -s.r, s.r * 2, s.r * 2); } ctx.restore(); }); requestAnimationFrame(draw); } function animateHue() { if (Math.abs(targetHue - hue) > 0.5) { hue += (targetHue - hue) * 0.01; updateColors(hue); shapes.forEach((s) => { s.color = `hsl(${hue},80%,${s.baseLight}%)`; }); } requestAnimationFrame(animateHue); } resize(); genShapes(hue); updateColors(hue); draw(); animateHue(); setInterval(() => { targetHue = Math.floor(Math.random() * 360); }, 5000);
Ad #1
Ad #2
Scroll to Top