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)};
}
}

Advertisements

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: