Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am have now this code: 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?

share|improve this question

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;
share|improve this answer
Very thanks Victor! – uvyre Sep 11 '11 at 23:34
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) – yoozer8 Apr 23 '12 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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.