Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change in mouse position when viewbox is added

I am currently learning and working in JavaScript and SVG and I am new to it. Here is my scenario

I have a div which has an SVG inside it.

<div id "O_div">
  <svg>
     <line x1= "0" x2 = "0" y1 ="0" y2 ="0">
     </line>
  <svg>
</div>

Now I want to know the mouse position relative to my div so I wrote following code

odiv = document.querySelector('#O_div');

XOffset = $(Odiv).position().left;
YOffset = $(Odiv).position().top;

   // And on my mouse move event 
            $('#O_div').mousemove(function(event) {
                var mouseX = event.clientX - XOffset;
                var mouseY = event.clientY - YOffset;
               // Here I am setting my line x and y coordinate equal mouseX and mouseY
               //So that line moves according to mouse move movement.           
            });

It is working fine. But the problem arises when I add a resize functionality to my div using query resizable.To resize my svg I added a viewBox option in it.Now my svg looks like this

<svg viewBox="0 0 450 154" preserveAspectRatio="xMinYMin meet">
</svg>

But now my mouse coordinate are not working fine and my line is a bit further from my mouse and it goes more far from my mouse when I increase the div size. Can any one kindly guide me how do I have to calculate my offset positions When I have a viewbox option in my svg.

Thanks any help and guidance will be appreciated.

like image 774
A_user Avatar asked Jul 30 '12 05:07

A_user


1 Answers

If you have a viewBox then you need to remember that mouse events provide values in the client coordinate system, not the coordinate system established via viewBox. This blogpost might help with explaining this a bit, and here's an example.

In short, what you need to do to get the coordinates in the current user space is this:

var m = El.getScreenCTM();

// note: assumes the root is an <svg> element, replace 
// document.documentElement with your <svg> element.
var p = document.documentElement.createSVGPoint(); 

p.x = evt.clientX;
p.y = evt.clientY;
p = p.matrixTransform(m.inverse());

The variable p will now contain the mouse position in the user coordinate system of the element El.

like image 68
Erik Dahlström Avatar answered Oct 20 '22 11:10

Erik Dahlström