Adding a Scrolling Background

Are you crying out for something more interesting than boilerplate setup code? Here’s the good news: From here on it gets much more interesting. Start by adding an animated starfield onto the page to give the game some space-like qualities.

You can create a scrolling starfield in a few ways, but in this case you need to be a little careful with the number of objects that get drawn on the screen because drawing too many sprites per frame slows down the game on mobile devices. One way around this is to create an offscreen canvas buffer, draw a bunch of random stars on that buffer, and then simply draw that starfield moving slowly down the canvas. You’ll be limited to a few different layers of moving stars, but this effect should be good enough for a retro shooter.

The Vagaries of HTML5 Performance
The performance question isn’t straightforward. One of the truisms of HTML5 is that you never know what method has better performance without trying it out. When deciding which way to implement a feature, your best bet is to go right to the source: Test it out! You can see the performance for different numbers of stars and ways to draw starfields at http://jsperf.com/prerendered-starfield. JSPerf.com is a great place to test your intuition. To see the results of the starfield test, scroll down the page and hit “Run Tests” to see the performance of the different runs. In this case, the answer isn't so cut and dry. Most desktops do better drawing individual ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.