There is one more caveat about using excanvas.js, and it’s a problem that I ran into
while creating the examples in this chapter. ExplorerCanvas initializes its own faux-
canvas interface automatically whenever you include the excanvas.js script in your
HTML page. But that doesn’t mean that Internet Explorer is ready to use it immediately.
In certain situations, you can run into a race condition where the faux-canvas interface
is almost, but not quite, ready to use. The primary symptom of this state is that Internet
Explorer will complain that “object doesn’t support this property or method” whenever
you try to do anything with a
element, such as get its drawing context.
The easiest solution to this is to defer all of your canvas-related manipulation until after
event fires. This may take a while—if your page has a lot of images or videos,
they will delay the
event—but it will give ExplorerCanvas time to work its magic.
A Complete Example
Halma is a centuries-old board game. Many variations exist. In this example, I’ve cre-
ated a solitaire version of Halma with nine pieces on a 9 × 9 board. In the beginning of
the game, the pieces form a 3 × 3 square in the bottom-left corner of the board. The
object of the game is to move all the pieces so they form a 3 × 3 square in the upper-
right corner of the board, in the least possible number of moves.
There are two types of legal moves in Halma:
• Take a piece and move it to any adjacent empty square. An “empty” square is one
that does not currently have a piece in it. An “adjacent” square is immediately
north, south, east, west, northwest, northeast, southwest, or southeast of the
piece’s current position. (The board does not wrap around from one side to the
other. If a piece is in the leftmost column, it cannot move west, northwest, or
southwest. If a piece is in the bottommost row, it cannot move south, southeast,
• Take a piece and hop over an adjacent piece, and possibly repeat. That is, if you
hop over an adjacent piece, then hop over another piece adjacent to your new
position, that counts as a single move. In fact, any number of hops still counts as
a single move. (Since the goal is to minimize the total number of moves, doing well
in Halma involves constructing, and then using, long chains of staggered pieces so
that other pieces can hop over them in long sequences.)
Figure 4-16 is a screenshot of the game itself; you can also play it online if you want to
poke at it with your browser’s developer tools.
So how does it work? I’m so glad you asked. I won’t show all the code here (you can
see it at http://diveintohtml5.org/examples/halma.js). I’ll skip over most of the gameplay
code itself, but I want to highlight a few parts of the code that deal with actually drawing
on the canvas and responding to mouse clicks on the
A Complete Example | 75
Download from Library of Wow! eBook <www.wowebook.com>