Get Relative Position of Mouse-Click in Canvas

31 08 2009

function getRelativePosition(e) {
var canvas = document.getElementById("canvas-diagram");
var scroll = document.body.scrollTop;
if( typeof( canvas.offsetParent ) != 'undefined' ) {
for( var posX = 0, posY = 0; canvas; canvas = canvas.offsetParent ) {
posX += canvas.offsetLeft;
posY += canvas.offsetTop;
}
return {x: e.clientX - posX, y: e.clientY - (posY-scroll)};
} else {
return {x: e.clientX - canvas.offsetLeft, y: e.clientY - (canvas.offsetTop-scroll)};
}
}


Actions

Information

3 responses

15 01 2010
Paul Chernoch

Thanks. I’ll give this a try.

15 01 2010
Paul Chernoch

It works! After all the stuff I read about Canvas, I am surprised I never came across any postings that mentioned offsetParent. You saved me a lot of trouble.

15 01 2010
phoenixblue

😀 glad this post was of help

Leave a comment