HTML and CSS Reference
In-Depth Information
If you have an image instead of a Canvas object, as with the background image, you can use jQuery to
create a new Canvas element and then draw the background image onto that Canvas element. As shown in List-
ing 17-7 , you can then return the pixel's image data from the Canvas context by calling getImageData and
passing in the coordinates of the image you want (such as the whole Canvas).
Listing 17-7: Returning pixel data from an image
Q.imageData = function(img) {
var canvas = $("<canvas>").attr({
width: img.width,
height: img.height })[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
return ctx.getImageData(0,0,img.width,img.height);
}
Retrieving the image data is a somewhat expensive operation, so unless you are updating the image it's best
to do this once and cache the result.
Add the code in Listing 17-7 to the bottom of quintus.js before the final return Q statement.
Playing with ImageData
Now that you have an ImageData object, how can you determine whether there is a “collidable” pixel at a
specific x and y location? Well, this task is equivalent to finding the color value at a specific pixel, and to do this
you need to do a little bit of simple math. ImageData objects have width and height attributes, but the main
meat of the information is in ImageData.data . This is a one-dimensional array of the actual pixel data, in
4-byte RGBA (red, green, blue, and alpha) chunks. This means all four elements of the array constitute 1 pixel
from the Canvas. Within those four elements, each of which represents a number from 0-255, you can examine
the red, green, blue, and alpha values that make up the pixel.
As Figure 17-2 shows, the alpha value determines how opaque the pixel is, with a value of 0 meaning the
pixel is completely transparent, whereas a value of 255 means it is completely opaque. You can use the alpha
value to determine if there is anything at that particular pixel in the image.
 
 
 
Search WWH ::




Custom Search