O'Reilly logo

Professional HTML5 Mobile Game Development by Pascal Rettig

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required