You can use .getBoundingClientRect
to get the canvas element position--including scrolling:
var BB=canvas.getBoundingClientRect();
Then you can get the mouse position relative to the canvas using event.clientX
and event.clientY
adjusted by the bounding box of the canvas element.
Note about borders and padding: You can click on the border of a canvas element and it will fire a canvas click event. This means [0,0] on the canvas is on the top-left corner of the canvas border. However the drawing area of a canvas is inside the border. Therefore, if you want to get the x,y of a click relative to the canvas drawing area you must also subtract the border size. The same is true about padding. Therefore if you want to get the x,y of a click relative to the canvas drawing area you must also subtract the padding size.
function handleMousedown(e){
var BB=canvas.getBoundingClientRect();
var x=e.clientX-BB.left-borderLeftWidth-paddingLeft;
var y=e.clientY-BB.top-borderTopWidth-paddingTop;
console.log(x,y);
}
To get the border and padding you can use .getComputedStyle
:
// a function using getComputedStyle to fetch resolved CSS values
function getStyle(elem,stylename){
return(
window
.getComputedStyle(elem,null)
.getPropertyValue(stylename)
);
}
// Fetch border and padding
var borderLeftWidth=getStyle(canvas,"border-left-width");
var borderTopWidth=getStyle(canvas,"border-top-width");
var paddingLeft=getStyle(canvas,"padding-left");
var paddingTop=getStyle(canvas,"padding-top");