Using Pixel Data to Detect Object Collisions
We can use the context.getImageData() function on two image objects to perform pixel-level collision detection
between the images.
Note
As of this writing, you must run this application from a web server in order to manipulate the local file image data on the canvas. If you are using the Safari browser (version 5.1.7 as of this writing), you can test the application on a local drive and it will function properly.
This is not a simple task, but it is ultimately straightforward. We
must remember that when we are using getImageData(), we are copying the color values
from the actual canvas and not the images themselves. For this reason, we
cannot simply use the Image object data as the source of our
collision testing but must copy that data from the canvas to a variable
and then use that data in the collision check.
Note
Visit the http://www.playmycode.com blog for further details about
collision detection and other game related topics. This site was
immensely helpful in finding a decent algorithm for getImageData().
Testing the alpha value of each pixel against each pixel in two
objects is an expensive operation. So, we are going to first test to see
whether our objects’ bounding boxes collide before we start to test each
pixel in each object. Here is the boundingBoxCollide() function we will use. It is
also used in Example 4-18,
and in Chapter 8 and Chapter 9 when we create games for the
Canvas:
functionboundingBoxCollide(object1,object2)
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access