HTML and CSS Reference
In-Depth Information
var startGame = function() {
window.addEventListener("load", function() {
All this code does is set up the available sprites, create a dummy startGame function that draws a ship on
the canvas to make sure everything is working correctly, and then listen for the load event on the window object
to call the Game.initialize function with the appropriate arguments.
Reload your index.html file (or run the code example game_class/index.html ) to see a lonesome
ship hanging out near the canvas element.
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 . 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 differ-
ent runs. In this case, the answer isn't so cut and dry. Most desktops do better drawing individual stars, whereas
iOS mobiles do better drawing the offscreen buffer, at the time of this writing at least. As canvas will get better
hardware acceleration across the board in the near future, it seems like a safe bet that the fillrate limited offscreen
buffer (as described in this section) will be substantially faster in the months and years to come.
Now break down a few of the necessary pieces before looking at the class as a whole. (You can skip to the
end of the section to see the full class if you want to peek ahead.)
The StarField class needs to do three main things. The first is to create an offscreen canvas. This is ac-
tually quite easy because canvas is just a regular DOM element with two attributes, width and height , and
can be created the same way as any other DOM elements:
var stars = document.createElement("canvas");
stars.width = Game.width;
Search WWH ::

Custom Search