By · Updated

Starfield Background

Warp Speed Star Streams in a Canvas Animation, With HTML, CSS and JS

No ratings yet

OneTask is free, with no sign-up, and built by one person.
If this tool saved you time, a coffee helps keep new ones coming.

How the Starfield Background works

A starfield background sends stars streaming out from the middle of a section, like the view from a ship flying through space. Pick the number of stars, the speed, the size and the colour, then copy the HTML, CSS and JavaScript.

The flying stars look is a classic for launch pages, games and anything about speed or space. It draws the eye to the centre, which is where the heading sits.

How the starfield background works

Every star has an x and y position between -1 and 1 and a depth between 0 and 1. Each frame the depth shrinks, and the star is drawn at its position divided by its depth, so as it gets closer it moves outward faster and grows brighter and bigger. When a star reaches the front it is sent back to the far distance at a new random spot, keeping the field full.

Motion preferences

For visitors who ask for reduced motion, the stars are drawn once as a still sky and never move. The canvas is hidden from screen readers, and the loop stops when the section is removed.

FAQ

How do I make a slow drifting starfield instead of warp speed?

Set the speed to 1 or 2. Stars will drift outward slowly, which reads as a calm night sky rather than a jump to hyperspace, and suits backgrounds behind long text.

Can I centre the starfield somewhere other than the middle?

Yes. Change cx and cy in the draw function to any point, for example the position of a logo or button, and the stars will stream out from there instead.

Does the starfield work on mobile?

Yes. The canvas matches the section size and pixel ratio, and a few hundred stars is cheap to draw on phones. On a tall narrow screen the stars spread by the larger side, so they still fill it.

Can I add coloured stars?

Yes. Give each star a colour when it spawns, for example picking from a short list of pale blues and yellows, and set ctx.fillStyle to that colour before drawing it.

See also: all Shadows & Motion tools, Layout & Spacing, Shapes & SVG, UI Components, Forms & Inputs, Colour.

Related tools