HTML and CSS Reference
In-Depth Information
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 jQuery.
Next, call
getContext
on the
canvas
element. A double-ampersand (
&&
) short circuit operator protects
you from calling a nonexistent method. This is used in the next
if
statement in case the visiting browser doesn't
support the
canvas
element. You always want to “fail loudly” in this case, so the players correctly blame their
browser instead of your code. “Failing loudly” means that instead of “failing silently” with a white screen and
an error hiding on the JavaScript console, the game explicitly pops up with a message that tells the user that
something went wrong.
There is a 3-D WebGL-powered rendering context available on desktop browsers (excluding Internet Ex-
plorer), but it is called
glcanval
and is available only on mobile Nokia devices at the time of this writing.
WebGL is another standard, separate from HTML5, that allows you to use hardware-accelerated 3-D graphics
in the browser.
Add the code from
Listing 1-3
to a file named
game.js
. You now can start playing with the
canvas
ele-
ment.