HTML and CSS Reference
In-Depth Information
Handling the Balls
Forthisexample, wewanttolisten foramouseclick ontheCanvas.Whentheuserclicks, 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
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 cap-
tured (at the time of this writing) the proper
x
and
y
mouse position on the Canvas:
function
function
createBall
(
event
) {
var
var
x
;
var
var
y
;
iif
(
event
.
pageX
||
event
.
pageY
) {
x
=
event
.
pageX
;
y
=
event
.
pageY
;
}
else
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
;
Becausewearecapturingthemouse
x
and
y
positionrelativetotheCanvas,youneedtomake
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
<canvas id=
"canvasOne"
width=
"450"
height=
"350"
style=
"position: absolute; top: 0px; left: 0px;"
>
Your browser does not support the HTML5 Canvas.
</canvas>
</canvas>
<canvas
<canvas id=
"canvasTwo"
width=
"450"
height=
"350"
style=
"position: absolute; top: 0px; left: 451px;"
>