HTML and CSS Reference
In-Depth Information
This application will need to be run from a local or remote web server,
as most browsers will throw an exception if an application attempts to
call getImageData() on a file—even in the same folder on a local ma-
chine. The current version of Safari (5.02) does not throw this error.
To create this simple application, we will use the tile sheet from earlier in this chapter.
The user will click on a spot on the tile sheet, highlighting a 32×32 square tile. That tile
can then be painted onto the bottom section of the canvas. To demonstrate pixel ma-
nipulation, we will set the color of the pixels to a new alpha value before they are painted
to the screen. This will be the humble beginning to making our own tile map editor.
Once again, we will use the tanks_sheet.png file from Figure 4-7 .
How is organized
The attribute is a single-dimensional array containing four bytes for
every pixel in the ImageData object. We will be using 32×32 tiles in our example appli-
cation. A 32×32 tile contains 1,024 pixels (or 1K of data). The attribute
for an ImageData instance that holds a 32×32 image would be 4,096 bytes (or 4K). This
is because a separate byte is used to store each of the red, green, blue, and alpha values
for each pixel. In our application, we will loop through each pixel and set its alpha
value to 128 . Here is the code we will use:
for (j=3; j<; j+=4){[j] = 128;
We start our loop at 3 , which is the fourth attribute in the array. The single-dimensional
array contains a continuous set of values for each pixel, so index 3 represents the alpha
value for the first pixel (because the array is 0 relative). Our loop then skips to every
fourth value in the array and sets it to 128 . Once the loop is complete, all pixels will
have an alpha value of 128 .
As opposed to other Canvas alpha manipulations where the alpha value
is between 0 and 1, the alpha value is between 0 and 255 when manip-
ulating it via the pixel color values.
A visual look at our basic application
Figure 4-13 is a screenshot of the simple Tile Stamper application we will create.
Figure 4-13 is running in Safari 5.1 locally. As of this writing, this is the
only browser that does not throw an exception when trying to manip-
ulate the pixel data of a locally loaded file when not run on a web server.
Search WWH ::

Custom Search