Free Background

Starfield

Hundreds of twinkling stars drift slowly on an HTML canvas. Lightweight JavaScript with no libraries; it pauses automatically for visitors who prefer reduced motion.

  • dark
  • canvas
  • animated
  • javascript
  • space

The code

Plain HTML, CSS and JavaScript with no dependencies. Copy a single file, or choose "Full file" for a complete page you can save as index.html and open in a browser.

<div class="space">
  <canvas id="stars"></canvas>
  <div class="content">
    <h1>Starfield</h1>
    <p>Canvas, 40 lines of JavaScript.</p>
  </div>
</div>

The AI prompt

Paste this into an AI coding tool to generate the same background, then ask it to adapt the colours, text or framework to your project.

Works with Claude · ChatGPT · Cursor · v0 · Bolt · Gemini
Create an animated starfield background with an HTML canvas and vanilla JavaScript (no libraries).

Requirements:
- A full-viewport wrapper with a radial-gradient night sky (#1b2735 at the bottom to #050816).
- A canvas absolutely positioned to fill the wrapper.
- On load and on window resize, set the canvas size to its displayed size and generate stars: roughly one star per 4000 square pixels, each with random x, y, radius (0.3-1.7px), upward speed and a random phase.
- In a requestAnimationFrame loop: clear the canvas, draw each star as a white circle whose opacity twinkles using a sine wave of time plus its phase, move it upward by its speed and wrap it to the bottom when it leaves the top.
- If the user has prefers-reduced-motion: reduce, draw a single static frame and do not loop.
- Centre a white heading and subtitle above the canvas.

Return a single HTML file with <style> and <script> tags.

How to build it, step by step

  1. 1

    Add a canvas inside a relatively positioned wrapper and stretch it with position: absolute and inset: 0.

  2. 2

    In a resize function, set canvas.width and canvas.height to the element's displayed size. Without this the canvas keeps its default 300x150 resolution and looks blurry.

  3. 3

    Generate star objects with random position, size, speed and phase. Scale the count with the canvas area so large screens are not sparse.

  4. 4

    In the draw loop, clear the canvas, then draw each star with ctx.arc. Vary ctx.globalAlpha with Math.sin(time + phase) to make stars twinkle independently.

  5. 5

    Move each star up a little every frame and wrap it back to the bottom when it leaves the top.

  6. 6

    Schedule the next frame with requestAnimationFrame, but skip the loop when prefers-reduced-motion is set.

Customisation tips

  • Change s.y -= s.speed to s.x += s.speed for horizontal drift.
  • Tint a few stars: pick the fill colour from an array such as ['#fff', '#c7d2fe', '#fde68a'].
  • Stop the loop with an IntersectionObserver when the section scrolls out of view to save battery.

More backgrounds