AJAX

Moderators: None (Apply to moderate this forum)
Number of threads: 61
Number of posts: 110

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
mouse coordinates from event Posted by Josh Code on 14 Feb 2011 at 11:53 AM
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:
<canvas id="display" width="600" height="400"
 onmousedown="mouseDown(event)"
>
</canvas>


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



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.