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 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 prerendered 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 security 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 filesystem, 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>
<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, represents our ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.