HTML and CSS Reference
In-Depth Information
make use of this information to offset the mouseX and mouseY values based on the position
of the <canvas> tag:
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 determine which exact tile was clicked. It will then call the highlight
Tile() function and pass 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 stamp the current selected tile in
that location on the tile map. Here is the function:
function onMouseClick(e) {
if (mouseY < 128){
//find tile to highlight
var col = Math.floor(mouseX / 32);
var row = Math.floor(mouseY / 32);
var tileId = (row*7)+(col+row);
highlightTile(tileId,col*32,row*32)
}else{
var col = Math.floor(mouseX / 32);
var row = Math.floor(mouseY / 32);
context.putImageData(imageData,col*32,row*32);
}
}
Let's take a closer look at the tile sheet click ( mouseY < 128 ).
To determine the tileId of the tile clicked on the tile sheet, we first need to convert the
x location of the mouse click to a number from 0‒7, and the y location to a number
from 0‒3. We do this by calling the Math.floor function on the result of the current
mouseX or mouseY location, divided by the tile width or height (they are both 32 ). This
will find the row and col of the clicked tile:
var col = Math.floor(mouseX / 32);
var row = Math.floor(mouseY / 32)
To find the tileId (the 0‒31 tile number of the tile sheet) of this row and column
combination, we need to use the following calculation:
TileId = (row*totalRows-1) + (col+row);
The actual calculation, with values for our application, looks like this:
var tileId = (row*7)+(col+row);
Search WWH ::




Custom Search