17 Feb

Starfield animation done in HTML 5

And here comes another useless but cool HTML 5 effect (See also: Water ripple effect done in HTML 5 and Snow effect done in HTML 5), the good old starfield animation you knew and loved from the old Windows 95 screen saver:

The algorithm is incredibly easy, the stars have a position and a size, and you just calculate starPosition += (starPosition – canvasCenter) * starSize and voila, the star moves according to its size (proximity to the screen) and position more or less realistically, no 3D calculations needed.
I discovered this algorithm a long time ago while playing around in Flash and now i finally built it in HTML 5.

The star drawing is done by drawing lines, this is slower than using a pre-drawn circle canvas, but it adds a bit more realism to the animation since the line is drawn between the old and newly calculated star position, which creates a much more visible movement of the stars.

Enough yapping, here is the code, just open it in a browser: Starfield animation in HTML5
If you are using this on your website and you are a nice person you can show it by giving me a credit (backlink) somewhere on your page, thank you!

6 thoughts on “Starfield animation done in HTML 5

    • by trying stuff out, i was doing complex calculations first when i noticed that a starfield animation is always moving stars depending on the center point, so i came up with this algorythm by implementing it in a bad way first and then step by step simplifying it.

    • yes, search for this line:
      context.strokeStyle = "rgba(255, 255, 255, " + Math.min(stars[x].size, 1) + ")";
      and replace the “255” values (from 0 to 255), the first one is red, then green, then blue.

Leave a Reply

Your email address will not be published. Required fields are marked *