SVG坐标

时间:2011-05-05 17:11:07

标签: javascript svg

请参阅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

当我点击左上角的矩形时,会生成上面的示例输出。

据我所知,getScreenCTM接口提供了元素的转换矩阵(此处为svg)。我把它作为第一行。第二行表示基于屏幕坐标的鼠标坐标。当我将变换矩阵应用于鼠标单击时,我希望该点将被转换为svg坐标。该值是上面的第3行。我不确定它是否正确。矩形具有y坐标10,并且单击事件仅在矩形内可用。那么基于svg的鼠标坐标怎么能低于10?


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

1 个答案:

答案 0 :(得分:3)

似乎是一个缺陷,具体取决于浏览器的缩放级别。提出了一个问题http://code.google.com/p/chromium/issues/detail?id=81995