39
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);
For example, if the user clicks on the point where mouseX = 50 and mouseY = 15, the
calculation would work like this:
col = Math.floor(50/32); // col = 1
row = Math.floor(15/32); // row = 0
tileId = (0*7)+(1+0); // tileId = 1
This position is the second tile on the tile sheet. The onMouseClick() function then
passes the tileId and col value multiplied by 32, and the row value multiplied by 32,
into the highlightTile() function. This tells the highlightTile() function the exact
tileId, row, and col the user clicked.
If the user clicked the tile map drawing area in the lower portion of the screen, the code
does the same row and column calculation. However, it then calls the putImageDa
ta() function and passes in the ImageData instance that holds the tile to stamp and the
top-left location to place the tile:
var col = Math.floor(mouseX / 32);
var row = Math.floor(mouseY / 32);
context.putImageData(imageData,col*32,row*32);
Pixel Manipulation | 175