Handling the Balls
For this example, we want to listen for a mouse click on the Canvas. When
the user clicks, we want to create a ball that flies across the Canvas
towards the piles of boxes. The first thing we need to do is create an
event listener for the mouseup
event:
theCanvas
.
addEventListener
(
"mouseup"
,
createBall
,
false
);
Next we need to create the createBall()
function. First, we get the
x and y position of the mouse
from the event object passed to createBall()
. Then we use some cross-browser
code to figure out the mouse position relative to the Canvas. The
following boilerplate code captured (at the time of this writing) the
proper x
and y
mouse position on the Canvas:
function
createBall
(
event
)
{
var
x
;
var
y
;
if
(
event
.
pageX
||
event
.
pageY
)
{
x
=
event
.
pageX
;
y
=
event
.
pageY
;
}
else
{
x
=
e
.
clientX
+
document
.
body
.
scrollLeft
+
document
.
documentElement
.
scrollLeft
;
y
=
e
.
clientY
+
document
.
body
.
scrollTop
+
document
.
documentElement
.
scrollTop
;
}
x
-=
theCanvas
.
offsetLeft
;
y
-=
theCanvas
.
offsetTop
;
mouseX
=
x
;
mouseY
=
y
;
Because we are capturing the mouse x
and y
position relative to the Canvas, you need to make sure that the <canvas>
element in the HTML page is
styled with top and left values so that the offsetLeft
and offsetTop
values are correct. For example, if
you position the Canvas inside a <div>
at 50,50
and leave the left
and top
style values at 0
, the mouse clicks will not be captured in
the correct locations:
<canvas
id=
"canvasOne"
width=
"450"
height=
"350"
style=
"position: ...
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.