This starfield animation simulates flying through space with stars streaming past the viewer. It uses HTML5 Canvas and JavaScript to project 3D star positions onto a 2D plane, creating a dynamic and immersive background effect.
How it works
Stars are initialized with random positions and depths (z-values). Each frame, the z-value decreases, moving them closer to the camera. The x and y coordinates are projected onto the canvas using a perspective formula: screenX = (x / z) * width + width/2. As stars approach (z → 0), they move outward and appear larger. Once a star passes the camera (z < 1), it is reset to a far distance with new random x,y, creating a continuous loop.
How to use it
Copy the entire HTML code into a new .html file.
The canvas automatically fills the window and handles resize events.
Adjust STAR_COUNT and SPEED variables in the script to change density and animation speed.
Integrate into your site by placing the canvas element as a full-page background behind other content.