Please note: this blog has been migrated to a new location at https://jakesgordon.com. All new writing will be published over there, existing content has been left here for reference, but will no longer be updated (as of Nov 2023)

Javascript Starfield

Sun, May 22, 2011

Continuing my exploration of the <canvas> element I took the Game.Runner class from my pong game and implemented an old-school 2d starfield.

You can use the blue buttons or the arrow keys to change the direction and speed of the stars.

Not much to explain really, its just an array of stars with random size, color and direction and a game loop that updates their position. Most of the work went into finding the right balance of ‘random’ when allocating stars. If you git clone the source you can play around with the Stars.Defaults.layers distribution:

  layers: [
    { percent:  30, size: { min: 0.4, max: 1.0 }, speed: { min:   1, max:   2 }, colors: ['#111', '#111', '#811'] }, // 1 in 3 get a tint of red
    { percent:  25, size: { min: 0.6, max: 1.2 }, speed: { min:   2, max:   4 }, colors: ['#333', '#333', '#833'] }, // 1 in 3 get a tint of red
    { percent:  15, size: { min: 0.8, max: 1.4 }, speed: { min:   4, max:   8 }, colors: ['#555', '#555', '#855'] }, // 1 in 3 get a tint of red
    { percent:  15, size: { min: 1.0, max: 1.6 }, speed: { min:   8, max:  16 }, colors: ['#777'] },
    { percent:   8, size: { min: 1.2, max: 1.8 }, speed: { min:  16, max:  32 }, colors: ['#999'] },
    { percent:   4, size: { min: 1.4, max: 2.0 }, speed: { min:  32, max:  64 }, colors: ['#BBB'] },
    { percent:   2, size: { min: 1.6, max: 2.2 }, speed: { min:  64, max: 128 }, colors: ['#DDD'] },
    { percent:   1, size: { min: 1.8, max: 2.4 }, speed: { min: 128, max: 256 }, colors: ['#FFF'] }
  ]

These <canvas> experiments are getting solid 60fps in modern browsers, but that’s to be expected because of their simplicity. Its a little worrying that the draw() method is 7 or 8ms which is halfway towards that magic 16ms limit (1000/60). I’m sure there is room for performance improvements in the way the canvas rendering is being done, so that’s something I’ll have to look closer at.

Another thing to look closer at is that even double buffered with solid 60fps there can be the occasional stuttering frame. I believe this is the javascript garbage collector kicking in, which we don’t have much control over, but presumably I could refactor my code to avoid allocating as many objects? Another thing to dig deeper into.

But for now, its just stars