15

How to get mouse cursor coordinates in raphaeljs library?

I'm trying something like:

rect.mousemove(function (event) {
        thisGrid.Popup.Show(event.layerX, event.layerY, ["clientX:", event.clientX, " clientY:", event.clientY, "\n", "layerX:", event.layerX, "layerY:", event.layerY, "\n",
            "pageX:", event.pageX, "pageY:", event.pageY].join(' '));

                        }
                    );

But all this properties return coordinates relative left upper corner of window or something.

Here is screenshot

enter image description here

Neir0
  • 12,849
  • 28
  • 83
  • 139

3 Answers3

13

I too had this issue a while back. You need to take into account the current div. In my case the div was called canvas. For the co-ordinates I used the following:

posx = e.pageX - $(document).scrollLeft() - $('#canvas').offset().left;
posy = e.pageY - $(document).scrollTop() - $('#canvas').offset().top;

Note: I was also using jQuery too hence the use of $. You can use document.getElementById if you prefer not to use jQuery.

Adam Holmes
  • 1,783
  • 3
  • 20
  • 32
  • 5
    it'd be super nice if Raphael just calculated these points (ie relative to Raphael.paper coordinates) and added them to the event object. – Eric H. Jul 30 '13 at 19:06
9

If you want coordinates relative to your div, try to use event.offsetX/offsetY

Fedor Skrynnikov
  • 5,521
  • 4
  • 28
  • 32
  • This worked for me, while the accepted answer (and several variations) did not. Event.offsetX is exactly in the coordinate system Raphael is using for drawing. (My div height and width match my Raphael init height and width -- I haven't tested whether that is part of why it works.) – Matt Jun 30 '13 at 03:05
  • 1
    In firefox event does not have offsetX, offsetY, but has layerX and layerY – blazkovicz Nov 11 '13 at 06:51
-1

compute with position of event source element (event.srcElement)

hungryMind
  • 6,931
  • 4
  • 29
  • 45