Getting Started with Canvas

You hopefully noticed a canvas tag in the middle of the HTML on the page (as shown in Listing 1-2):

    <canvas id='game' width='320' height='480'></canvas>

This is where all the action for the game takes place—so much exciting stuff you can do in such an unassuming tag.

The tag has an id for easy reference along with a width and height. Unlike most HTML elements, you generally never want to add a CSS width and height onto canvas elements. Those styles visually resize your canvas but do not affect the pixel dimensions of the canvas, which is controlled by the width and height on the element. Most of the time you should leave these alone.

Accessing the Context

Before you can do any drawing onto canvas, you need to fetch the context from the canvas element. The context is the object that you actually make API calls against (not the canvas element itself.) For 2-D canvas games, you can pull out the 2-D context, as shown in Listing 1-3.

Listing 1-3: Accessing the rendering context

var canvas = document.getElementById('game');

var ctx = canvas.getContext && canvas.getContext('2d');
if(!ctx) {
   // No 2d context available, let the user know
   alert('Please upgrade your browser');
} else {
  startGame();
}
function startGame() {
 // Let's get to work
}

First, grab the element from the document. These initial chapters use built-in browser methods for all DOM (Document Object Model) interaction; later you are introduced to how to do the same things more concisely using ...

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.