About this snippet

Engage your visitors with this moving starfield background. We built it using HTML5 Canvas, so it performs beautifully and adds depth to your dark mode sections.

Size
2.1 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
235
<div class="starfield-wrapper">
  <canvas id="star-canvas"></canvas>
  <div class="star-content">
    <h2>Explore The Cosmos</h2>
    <p>This beautiful background uses HTML5 Canvas to render moving stars.</p>
  </div>
</div>
*, *::before, *::after {
  box-sizing: border-box;
}

body {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  background: #f3f4f6;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
  padding: 20px;
}

.starfield-wrapper {
  position: relative;
  width: 100%;
  max-width: 800px;
  height: 400px;
  background: #0f172a;
  overflow: hidden;
  border-radius: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.2);
}

#star-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.star-content {
  position: relative;
  z-index: 2;
  text-align: center;
  color: #ffffff;
  pointer-events: none;
  padding: 20px;
}

.star-content h2 {
  font-size: 2.5rem;
  margin: 0 0 10px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.star-content p {
  color: #cbd5e1;
  font-size: 1.125rem;
  margin: 0;
}
const canvas = document.getElementById("star-canvas");
const ctx = canvas.getContext("2d");

// Set fixed dimensions for the demo
canvas.width = 800;
canvas.height = 400;

const stars = new Array();

for (let i = 0; i < 150; i++) {
  const star = new Object();
  star.x = Math.random() * canvas.width;
  star.y = Math.random() * canvas.height;
  star.radius = Math.random() * 1.5;
  star.speed = Math.random() * 0.5 + 0.1;
  stars.push(star);
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ffffff";
  
  stars.forEach(function(s) {
    ctx.beginPath();
    ctx.arc(s.x, s.y, s.radius, 0, Math.PI * 2);
    ctx.fill();
    
    // Move the star down
    s.y += s.speed;
    
    // Reset star to top when it falls off screen
    if (s.y > canvas.height) {
      s.y = 0;
      s.x = Math.random() * canvas.width;
    }
  });
  
  window.requestAnimationFrame(draw);
}

draw();
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save