HTML and CSS Reference
In-Depth Information
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 opera-
tion. So, we are going to first test to see whether our objects' bounding boxes collide before
westarttotesteachpixelineachobject.Hereisthe
boundingBoxCollide()
functionwewill
use. It is also used in
Example 4-18
,
and in
Chapter 8
and
Chapter 9
when we create games
for the Canvas:
function
function
boundingBoxCollide
(
object1
,
object2
) {
var
var
left1
=
object1
.
x
;
var
var
left2
=
object2
.
x
;
var
var
right1
=
object1
.
x
+
object1
.
width
;
var
var
right2
=
object2
.
x
+
object2
.
width
;
var
var
top1
=
object1
.
y
;
var
var
top2
=
object2
.
y
;
var
var
bottom1
=
object1
.
y
+
object1
.
height
;
var
var
bottom2
=
object2
.
y
+
object2
.
height
;
iif
(
bottom1
<
top2
)
return
return
(
false
false
);