HTML and CSS Reference
In-Depth Information
Step 3 is where the real magic happens: being able to check for intersection against transparent or opaque pixels
allows your game to overlay images on top of each other, and you can still determine, at pixel granularity, which
image/object was selected (see Figure 5-3 ).
Figure 5-3. Valid areas for bounding-box picking vs. pixel-perfect picking. Since the bounding-box for an object is larger
than its discrete bounds, a selection does not need to be pixel perfect
Loading Pixel Data
The cornerstone of your picking process is assuming that your images contain alpha values, and that you can access
those pixels during a pick operation to determine if the selected point is in a transparent or opaque part of the image,
which you generally assume is loaded this way:
var img = new Image();
img.onload = function(){alert('loaded!”);}
img.src = filename;
The problem here is that in JavaScript you don't directly handle the pixel data; it's handled behind the scenes on
your behalf.
To get the data then, you need to do some extra work. You could start by writing a JavaScript PNG decoder, but
that would be massive overkill, considering PNGs support lossless compression, meaning you'd have to implement
the entire DEFLATE codec by hand. Since you're really only concerned with the alpha values of an image, you could
store the alpha channel in a separate .RAW file that you fetch in parallel; however, this would increase the transfer and
asset size of the app.
For the sake of your purpose, you ignore those two options, and instead decide to keep the code footprint and
transfer sizes low by using the canvas element to fetch the data. To do this, you create an off-screen canvas, render
your image to it, and fetch the pixels of the canvas object back to memory (see Listing 5-10).
Listing 5-10. Fetching the image data by using an off-screen canvas
var offScreenCanvas= document.createElement('canvas');
var fetch_ctx = offScreenCanvas.getContext('2d');
// set a max size for our offscreen fetch canvas
offScreenCanvas.width = 128;
offScreenCanvas.height = 128;
function fetchImageData(imgObject, imgwidth,imgheight)
Search WWH ::

Custom Search