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:

function boundingBoxCollide(object1, object2) {
    var left1 = object1.x;
    var left2 = object2.x;
    var right1 = object1.x + object1.width;
    var right2 = object2.x + object2.width;
    var top1 = object1.y;
    var top2 = object2.y;
    var bottom1 = object1.y + object1.height;
    var bottom2 = object2.y + object2.height;

    if (bottom1 < top2) return(false);
    if (top1 > bottom2) return(false);

    if (right1 < left2) return(false);
    if (left1 > right2) return(false);

    return(true);

}

As you can see, this function takes in two parameters. These are the two logical objects that we want to test the collision on. As long as the object instances include x, y, width, and height attributes, the function will perform properly. First let’s examine the objects that we are going to test collisions on.

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.