I am have now this code: http://jsfiddle.net/DK67k/2/ In here is 2D tile map and when you click on tile you get coordinates on alert. But for get precises coordinate you need click on top left tile(tiles is 16x16) and if I click on bottom right tile I am get second tile coordinates.

Maybe anyone have idea how to fix this?


2 Answers 2


When you rely on mouse coordinates on the web browser it takes in count the whole screen. So you must not rely on absolute mouse coordinates, you have to subtract the canvas offset on the page from it to use it on the 2D Tile Map.

An example of code

var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
  • \$\begingroup\$ Victor, since you seemed to understand the question, would you mind editing it to make it clearer? I started to, but then I realized I really don't understand what is being asked (I'm guessing I'm not the only one) \$\endgroup\$
    – yoozer8
    Apr 23, 2012 at 22:38
window.addEventListener("mousemove", function(e)
    mouse.x = e.offsetX || e.layerX;   //refers to x relative to canvas
    mouse.y = e.offsetY || e.layerY;   // y relative to canvas
    // update for click here - it is should not be done each frame

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .