htmlintermediatemit
Starfield
A twinkling starfield with depth.
2.6k1.1k868578
About this module
Stars at varying depths drift diagonally and twinkle — a classic space background effect.
#canvas#2d#stars#space#twinkle
Source code
Installation
- 1
Create the files
Create `index.html`, `style.css` and `script.js` in the same folder.
- 2
Paste the code
Copy each file's source into its matching file.
- 3
Open in the browser
Open `index.html` in any modern browser.
Usage
- 1
Copy the HTML
Paste the canvas markup where you need it.
<link rel="stylesheet" href="style.css" /> <script src="script.js"></script> <div class="mh-canvas-wrap" style="background:#0b1020"> <canvas id="mh-canvas"></canvas> <span class="mh-canvas-label">STARFIELD</span> </div> - 2
Wire up the script
Include `script.js` before the closing body tag.
const canvas = document.getElementById("mh-canvas"); const ctx = canvas.getContext("2d"); let w, h, dpr = Math.min(window.devicePixelRatio || 1, 2); const CONFIG = { count: 180, speed: 0.25 }; let stars = []; function resize() { const rect = canvas.parentElement.getBoundingClientRect(); w = rect.width; h = rect.height; canvas.width = w * dpr; canvas.height = h * dpr; canvas.style.width = w + "px"; canvas.style.height = h + "px"; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); stars = Array.from({ length: CONFIG.count }, () => ({ x: Math.random() * w, y: Math.random() * h, r: Math.random() * 1.6 + 0.4, d: Math.random() * 0.5 + 0.5, tw: Math.random() * Math.PI * 2 })); } function tick() { ctx.clearRect(0, 0, w, h); for (const s of stars) { s.x -= CONFIG.speed * s.d; s.y += CONFIG.speed * s.d * 0.4; if (s.x < 0) { s.x = w; s.y = Math.random() * h; } if (s.y > h) s.y = 0; s.tw += 0.03; const alpha = 0.4 + Math.abs(Math.sin(s.tw)) * 0.6; ctx.beginPath(); ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2); ctx.fillStyle = "rgba(255,255,255," + alpha + ")"; ctx.fill(); } requestAnimationFrame(tick); } resize(); window.addEventListener("resize", resize); tick();