The Colliding Objects
We are going to use two PNG image files as the design for our objects. They will both be 48-pixel by 48-pixel images. The first will be a blue plus sign, and the second will be a red circle with a round “bite” taken out of it. Figure 4-19 shows the drawing objects for our pixel-level collision detection.
Figure 4-19. The drawing objects for our pixel-level collision detection
We will create two objects to hold the data for these images:
var
blueObject
=
{};
var
redObject
=
{};
blueObject
.
x
=
0
;
blueObject
.
y
=
200
;
blueObject
.
dx
=
2
;
blueObject
.
width
=
48
;
blueObject
.
height
=
48
;
blueObject
.
image
=
new
Image
();
blueObject
.
image
.
src
=
"blueplus.png"
;
redObject
.
x
=
348
;
redObject
.
y
=
200
;
redObject
.
dx
=-
2
;
redObject
.
width
=
48
;
redObject
.
height
=
48
;
redObject
.
image
=
new
Image
();
redObject
.
image
.
src
=
"redcircle.png"
;
We also need to draw each of the two images to the Canvas briefly
and store the ImageData
value for
each:
context
.
drawImage
(
blueObject
.
image
,
0
,
0
);
blueObject
.
blueImageData
=
context
.
getImageData
(
0
,
0
,
blueObject
.
width
,
blueObject
.
height
);
context
.
clearRect
(
0
,
0
,
theCanvas
.
width
,
theCanvas
.
height
);
redObject
.
x
=
348
;
context
.
drawImage
(
redObject
.
image
,
0
,
0
);
redObject
.
redImageData
=
context
.
getImageData
(
0
,
0
,
redObject
.
width
,
redObject
.
height
);
context
.
clearRect
(
0
,
0
,
theCanvas
.
width
,
theCanvas
.
height
);
We draw at 0,0 for ease of use, but these could be drawn on a second hidden canvas or anywhere ...
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.