Change mouse position when adding viewport

I am currently learning and working in JavaScript and SVG, and I am new to this. Here is my script

I have a div that has SVG in it.

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

Now I want to know the position of the mouse relative to my div, so I wrote the 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 occurs when I add resizing functionality to my div using a resizable request. To resize my svg, I added the viewBox parameter to it. Now my svg looks like this:

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

But now my mouse coordinate is not working fine, and my line is a little further from my mouse, and it goes far from my mouse when I increase the size of the div. Can someone kindly explain to me how I can calculate my offset positions when I have a view option in my svg.

, .

+5
1

viewBox, , , , viewBox. blogpost , .

, , :

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

p El.

+9

All Articles