Reputation: 21
I have a canvas element and when i click on it i get the click position with e.clientX(Y) or e.screenX(Y). Something strange is happening. Y value is always too high. Please look at this image: http://img840.imageshack.us/img840/268/eventq.jpg. Any ideia why is it so high?
Upvotes: 0
Views: 761
Reputation: 38526
You just need to take the ClientX and Y and subtract the position of the canvas from them.
This example is unnecessarily verbose, just to show the steps:
var canvas = document.getElementById('game');
var canvasX, canvasY;
canvas.addEventListener('click', function(event) {
canvasX = canvas.offsetLeft;
canvasY = canvas.offsetTop;
var eventX = event.clientX;
var eventY = event.clientY;
var relX = eventX - canvasX;
var relY = eventY - canvasY;
alert('X = ' + relX + ', Y = ' + relY);
});
Working sample: http://jsfiddle.net/JfhJF/
Upvotes: 1
Reputation: 1586
I'm pretty sure you can tell what's happening. You do not have the coordinates relative to your canvas, but relative to your viewport. It also depends on your browser whether or not they include padding.
Convert them to normal coordinates. In your case this involves substracting the offset of the canvas.
Upvotes: 0