HTML and CSS Reference
In-Depth Information
var
var
mouseX
;
var
var
mouseY
;
We will also set up two event listener functions and attach them to the
theCanvas
object:
theCanvas
.
addEventListener
(
"mousemove"
,
onMouseMove
,
false
false
);
theCanvas
.
addEventListener
(
"click"
,
onMouseClick
,
false
false
);
In the HTML, we will set up a single
Canvas
object:
<canvas
<canvas id=
"canvas"
width=
"256"
height=
"256"
style=
"position: absolute;
top: 50px; left: 50px;"
>
Your browser does not support HTML5 Canvas.
</canvas>
</canvas>
In the JavaScript portion of our code, we will define the canvas:
theCanvas
=
document
.
getElementById
(
"canvas"
);
Notice that we set the
<canvas>
position to
top: 50px
and
left: 50px
. This will keep the
application from being shoved up into the top-left corner of the browser, but it also gives us a
chancetodemonstratehowtofindcorrectmouse
x
and
y
valueswhenthe
<canvas>
tagisnot
in the top-left corner of the page. The
onMouseMove
function will make use of this informa-
tion to offset the
mouseX
and
mouseY
values, based on the position of the
<canvas>
tag:
function
function
onMouseMove
(
e
) {
mouseX
=
e
.
clientX
-
theCanvas
.
offsetLeft
;
mouseY
=
e
.
clientY
-
theCanvas
.
offsetTop
;
}
The
onMouseClick
function will actually do quite a lot in our application. When the mouse
button is clicked, this function will determine whether the user clicked on the tile sheet or on
the tile map drawing area below it. If the user clicked on the tile sheet, the function will de-
terminewhichexacttilewasclicked.Itwillthencallthe
highlightTile()
functionandpass
in the ID (0-31) of the tile clicked, along with the
x
and
y
locations for the top-left corner of
the tile.
If the user clicked in the lower portion of the tile map drawing area, this function will again
determine which tile the user clicked on and will stamp the current selected tile in that loca-
tion on the tile map. Here is the function:
function
function
onMouseClick
(
e
) {
iif
(
mouseY
<
128
){
//find tile to highlight
var
var
col
=
Math
.
floor
(
mouseX
/
32
);