HTML5 Canvas [62]
The first task highlightTile() tackles is redrawing the tile sheet at the top of the screen:
context.fillStyle = "#aaaaaa";
context.fillRect(0,0,256,128);
drawTileSheet();
It does this to delete the red box around the current tile, while preparing to draw a new red box around the tile represented by the tileId passed in.
The drawTileSheet() function then paints the tanks_sheet.png file to the canvas starting at 0,0:
function drawTileSheet(){
context.drawImage(tileSheet, 0, 0);
}
Next, the highlightTile() function copies the new pixel data (with no red line around it yet) from the canvas and places it in the ImageData instance:
ImageData = context.getImageData(x,y,32,32);
The ImageData variable now contains a copy of the pixel data for the tile from the canvas. We then loop through the pixels in ImageData.data (as described previously in How ImageData.data is organized), and set the alpha value of each to 128.
Finally, now that the ImageData variable contains the correct pixels with the altered alpha values, we can draw the red line around the tile that’s been selected to stamp on the tile map:
var startX = Math.floor(tileId % 8) *32;
var startY = Math.floor(tileId / 8) *32;
context.strokeStyle = "red";
context.strokeRect(startX,startY,32,32)
Example 4-16 is the entire set of code for this application.
Example 4-16. The Tile Stamper application
NOTE
As of this writing, you must run this application from a web server in order to manipulate the local tanks_sheet.png file on the canvas. If you are using the Safari browser (version 5.1 as of this writing), you can test the application on a local drive