HTML and CSS Reference
In-Depth Information
Application Tile Stamper
We are going to create a simple application that will allow the user to highlight a box around
It will not be a full-blown editing application by any means—it's just a demonstration of one
use of the ImageData object.
This application will need to be run from a local or remote web server, because most browsers will
throw an exception if an application attempts to call getImageData() on a file—even in the same
folder on a local machine. The current version of Safari (6.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 manipulation, 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 for 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 application.
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 < imageData . data . length ; j += 4 ){
imageData . data [ 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 . When the loop is complete, all pixels will have an alpha value of 128 .
Search WWH ::

Custom Search