I\'ve spent the whole day trying to get a click over my canvas to return the pixel xy offset. What a mission this has been!
This is what I\'ve ended up with:
<
As you've discovered, border size is counted in calculating mouse position.
So wrap your canvas in a container div with the container div having the 20px border.
This takes away the extra calculations needed if the border were on the canvas itself.
Note: I put the styles for #borderDiv & #myCanvas in a Style section in the Header.
var canvas = document.getElementById('myCanvas');
canvas.addEventListener('click', on_canvas_click, false);
var context=canvas.getContext('2d');
context.fillStyle='red';
context.fillRect(0,0,10,1);
context.fillRect(0,0,1,10);
function getNumericStyleProperty(style, prop) {
return parseInt(style.getPropertyValue(prop),10);
}
function on_canvas_click(ev) {
var boundingRect = ev.target.getBoundingClientRect();
var x = ev.clientX - boundingRect.left,
y = ev.clientY - boundingRect.top;
$("#logX").text("x="+x);
$("#logY").text("y="+y);
}
#borderDiv{margin:0px; width:100px; height:1000px; border:20px solid black;}
x
y