HTML and CSS Reference
In-Depth Information
Detecting mouse interactions and the canvas
Recall that back in the canvasApp() function, we set an event listener for the mouseup
action with the event handler function set to eventMouseUp . We now need to create that
theCanvas.addEventListener("mouseup",eventMouseUp, false);
The first thing we do in the eventMouseUp() function is test to find the x and y locations
of the mouse pointer when the button was pressed. We will use those coordinates to
figure out whether the user clicked on any of the puzzle pieces.
Since some browsers support the layerX / layerY properties of the event object, and
others support the offsetX / offsetY properties, we need to support both. No matter
which one is set, we will use those properties to set our mouseX and mouseY variables to
the x and y locations of the mouse pointer:
function eventMouseUp(event) {
var mouseX;
var mouseY;
var pieceX;
var pieceY;
if ( event.layerX || event.layerX == 0) { //Firefox
mouseX = event.layerX ;
mouseY = event.layerY;
} else if (event.offsetX || event.offsetX == 0) { // Opera
mouseX = event.offsetX;
mouseY = event.offsetY;
Creating hit test point-style collision detection
Now that we know where the user clicked, we need to test whether that location “hits”
any of the puzzle pieces. If so, we set the selected property of that piece to true . What
we are going to perform is a simple hit test point -style hit detection. It will tell us whether
the x , y position ( point ) of the mouse is inside ( hits ) any one of the puzzle pieces when
the mouse button is clicked.
First, we create a local variable named selectedList that we will use when we need to
swap the pieces in the board array. Next, we will use a set of two nested for:next loops
to traverse through all the pieces in the board array. Inside the for:next loops, the first
thing we do is find the top-left corner x and y points of the current piece pointed to
by board[c][r] . We calculate those values and put them into the placeX and placeY
Search WWH ::

Custom Search