We also need to draw each of the two images to the Canvas briefly and store the Image
Data value for each:
context.drawImage(blueObject.image, 0, 0);
blueObject.blueImageData=context.getImageData(0, 0, blueObject.width,
context.drawImage(redObject.image, 0, 0);
redObject.redImageData=context.getImageData(0, 0, redObject.width,
We draw at 0,0 for ease of use, but these could be drawn on a second hidden canvas or
anywhere on the current canvas. We want to erase them right after we place them because
we need to store only the pixel color data for each. Specifically, we will be using every
fourth item in the array of pixel data. This is the transparency value of the pixel.
How We Will Test Collisions
We will employ a simple setTimeout loop to move these objects closer and closer to‐
gether. As the bounding boxes of each collide, our code will then drop into an algorithm
that will test the alpha value on each pixel at the overlap between the objects. If this
alpha value is not 0, we know that the objects have collided.
Checking for Intersection Between Two Objects
After we have detected that we have a bounding box collision, we can simply loop
through all of the pixels in each ImageData set, find the ones that match, and then check
to see whether the alpha value for that pixel is 0. The problem with this approach is that
it is slow and pretty much unusable for objects larger than a few pixels in width and
height. Our 48×48 pixel images are each composed of 2,304 individual pixels. That is
far too many to loop through on each frame tick, even for a single collision test. What
we are going to do first is find where the two bounding boxes for our objects intersect
and then check only those pixels.
Figure 4-20 shows an area of intersection where there would be a pixel-based collision.
184 | Chapter 4: Images on the Canvas