SVG Coordinators

See jsfiddle

sample output:
offset based on svg x:12 y:34
mouse click based on screen x:22 y:38
mouse coord based on svg x:10 y:4

The above output is output when I click on the rectangle in the upper left corner.

As I understand it, the getScreenCTM interface provides a transformation matrix for the element (svg here). I got it as the first line. The second line indicates the coordinate of the mouse based on the screen coordinate. When I apply the transformation matrix to a mouse click, I expect the point to be translated into the svg coordinate. This value is the third line above. I'm not sure this is a correspondent. The rectangle has a y coordinate of 10, and the click event is only within the rectangle. So, how will svg-based mouse coordination be below 10?

Thanks, BSR.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head> 
</head>
<body>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
<h1>sdsd</h1>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" height="200">
    <g fill="none" stroke="black" stroke-width="1" >
        <!-- Draw the axes of the original coordinate system -->
        <line x1="0" y1=".5" x2="400" y2=".5" />
        <line x1=".5" y1="0" x2=".5" y2="150" />
    </g>

    <g >
        <rect class="drag resize" x="10" y="10" width="100" height="50" fill="#c66" />
    </g>
</svg>

    <h2 id="op"></h2> 

          <script type="text/javascript" src="vb.js"></script>
</body>
</html>

var svg   = document.getElementsByTagName('svg')[0];
var svgNS = svg.getAttribute('xmlns');
var pt    = svg.createSVGPoint();
var el1 = document.getElementsByTagName('rect')[0];

var log_svgcursorPoint,
    log_mouseclick,
    log_mousecoord;


function svgcursorPoint(evt){
    pt.x = evt.clientX; pt.y = evt.clientY;
    var a = svg.getScreenCTM();
    log_svgcursorPoint = "offset based on svg"+ " x:" + a.e +" y:" + a.f;
    var b = a.inverse();
    return pt.matrixTransform(b);
};

    (function(el){
        el.addEventListener('mousedown',function(e){
            log_mouseclick = "mouse click based on screen"+ " x:" + e.clientX +" y:" + e.clientY ;
            var svgmouse   = svgcursorPoint(e);    
            log_mousecoord = "mouse coord based on svg"+ " x:" + svgmouse.x +" y:" +svgmouse.y;
            document.getElementById('op').innerHTML = log_svgcursorPoint + "<br>" + log_mouseclick + "<br>" + log_mousecoord;
        },false);
    })(el1);
+3
source share

All Articles