HTML and CSS Reference
Canvas's context element is useful for defining 2D drawing and you can use it for feature
detection. Simply encapsulate the context variable in an if statement, and it will check to
make sure the Canvas variable has a getContext method. Here's what basic feature de-
tection looks like with Canvas.
var canvas = document . getElementById ( 'canvas' );
if ( canvas . getContext && canvas . getContext ( '2d' ))
var ctx = canvas . getContext ( '2d' );
This checks both getContext and getContext('2d') because some mobile
browsers return true for the getContext test but false for the getCon-
IE7 and IE8 will crash when using Canvas API commands unless you use explorercanvas
( http://code.google.com/p/explorercanvas/wiki/Instructions ) . To use it, click the download
tab, unzip the files, put excanvas.js in your root directory, and add a script element loading
excanvas.js inside a conditional comment targeting IE. IE9 gives great support, and IE10's
support is looking quite solid. Our disclaimer for explorercanvas is that with it you can do
simple animations, but more advanced support (such as that needed for the Canvas Rico-
chet game tutorial) might not work.
Now that you have your index.html file set up and you understand exactly what the Canvas
context is, it's time to create your first game, Canvas Ricochet.
6.2. Creating a Canvas game
Your first Canvas game, shown in figure6.4 , will make use of overlap detection, animation,
keyboard/mouse/touch controls, and some polish.