HTML and CSS Reference
In-Depth Information
Creating a Dynamic Tile Sheet at Runtime
In Chapter 4 ,webrieflyexaminedtwoprincipleswecanusetohelpeliminatetheneedtopre-
createrotationsofobjectsintilesheets.Creatingthesetypesoftilesheetscanbecumbersome
and use up valuable time that's better spent elsewhere in the project.
The idea is to take a single image of a game object (e.g., the first tile in the medium rock tile
sheet), create a dynamic tile sheet at runtime, and store it in an array rather than using the pr-
erendered image rotation tiles.
To accomplish this, we need to use a second canvas as well as the getImageData() and
putImageData() Canvas functions. Recall from Chapter 4 that getImageData() throws a se-
curity error if the HTML page using it is not on a web server.
Currently, only the Safari browser doesn't throw this error if the file is used on a local filesys-
tem, so we have separated this functionality from the Geo Blaster Extended game and simply
demonstrate how it could be used instead of replacing all the tile sheets in the game with this
type of prerendering.
We start by creating two <canvas> elements on our HTML page:
<body>
<body>
<div>
<div>
<canvas
<canvas id= "canvas" width= "256" height= "256" style= "position: absolute; top:
50px; left: 50px;" >
Your browser does not support HTML5 Canvas.
</canvas>
</canvas>
<canvas
<canvas id= "canvas2" width= "32" height= "32" style= "position: absolute; top:
256px; left: 50px;" >
Your browser does not support HTML5 Canvas.
</canvas>
</canvas>
</div>
</div>
</body>
</body>
The first <canvas> , named canvas , represents our hypothetical game screen, which displays
the precached dynamic tile sheet animation.
Thesecond <canvas> ,named canvas2 ,isusedasadrawingsurfacetocreatethedynamictile
frames for our tile sheet.
We need to separate context instances in the JavaScript, one for each <canvas> :
var
var theCanvas = document . getElementById ( "canvas" );
var
var context = theCanvas . getContext ( "2d" );
Search WWH ::




Custom Search