mouse coordinates from event - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

mouse coordinates from event

Josh CodeJosh Code Posts: 675Member
I want to get coordinates from an event object for drawing on an HTML 5 canvas element but am having lots of trouble. I get the event object from the event attribute like this:
[code]


[/code]

How do you get the x and y coordinates from an event object?

Below are some functions I tried to use. getOffsetX, getOffsetY take an element in and are supposed to return the positions of them relative to the page but I'm not sure if they work. The getXFromEvent and getYFromEvent are supposed to get the x and y coordinates from an event object. They work somewhat. The pixel coordinates I want to use when drawing on the canvas I'm calculating using getXFromEvent(event)-getOffsetX(canvasElement) and similar for the y.
[code]
function getOffsetX( el )
{
var _x = 0;
while( el && !isNaN( el.offsetLeft ) )
{
_x += el.offsetLeft - el.scrollLeft;
el = el.parentNode;
}
return _x;
}

function getOffsetY( el ) {
try
{
var _y = 0;
while( el && !isNaN( el.offsetTop ) )
{
_y += el.offsetTop - el.scrollTop;
el = el.parentNode;
}
return _y;
}
catch (exc)
{
alert("sideMenu.js, getOffsetY problem, "+exc);
return 0;
}
}

function getXFromEvent(e)
{
var x=0;

if (e.pageX)
x=e.pageX;

return x;
}

function getYFromEvent(e)
{
var y=0;

if (e.pageY)
y=e.pageY;

return y;
}
[/code]
Sign In or Register to comment.