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!

10 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.

  1. I’m having trouble… on a particular page of my site (credit will be given, BTW), I could use the starfield to flow FROM the center point instead of following the cursor. Can you advise?

    • Just remove this block of code and the animation will not react to mouse movements anymore:

      // when mouse moves over canvas change middle point of animation
      canvas.onmousemove = function(event) {
      dirX = event.offsetX,
      dirY = event.offsetY;

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.