HTML and CSS Reference
In-Depth Information
Creating a Dynamic Tile Sheet at Runtime
In Chapter 4 , we briefly examined two principles we can use to help eliminate the need
to precreate rotations of objects in tile sheets. Creating these types of tile sheets can be
cumbersome and use up valuable time that's better spent elsewhere in the project.
The idea will be 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 prerendered image rotation tiles.
To accomplish this, we need to make use of a second canvas, as well as the getImage
Data() and putImageData() Canvas functions. If you recall from Chapter 4 , getImage
Data() will throw a security error if the HTML page using it is not on a web server.
Currently, only the Safari browser will not throw this error if the file is used on a local
filesystem. For this reason, we have separated this functionality from the Geo Blaster
Extended game and will simply demonstrate how it could be used instead of replacing
all the tile sheets in the game with this type of prerendering.
We will start by creating two <canvas> elements on our HTML page:
<body>
<div>
<canvas id="canvas" width="256" height="256" style="position: absolute; top:
50px; left: 50px;">
Your browser does not support HTML5 Canvas.
</canvas>
<canvas id="canvas2" width="32" height="32" style="position: absolute; top:
256px; left: 50px;">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</body>
The first <canvas> , named canvas , will represent our hypothetical game screen, which
will be used to display the precached dynamic tile sheet animation.
The second <canvas> , named canvas2 , will be used as a drawing surface to create the
dynamic tile frames for our tile sheet.
We will need to separate context instances in the JavaScript, one for each <canvas> :
var theCanvas = document.getElementById("canvas");
var context = theCanvas.getContext("2d");
var theCanvas2 = document.getElementById("canvas2");
var context2= theCanvas2.getContext("2d");
We will use the mediumrocks.png file ( Figure 9-9 ) from the Geo Blaster Extended game
as our source for the dynamic tile sheet. Don't let this confuse you. We are not going
to use all five tiles on this tile sheet—only the first tile.
Search WWH ::




Custom Search