2011-05-05 19 views
3

請參閱產生jsfiddleSVG coordiantes

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?

謝謝, 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); 
+1

當我點擊Firefox 4.0.2pre的左上角時,我看到了'基於svg x:12 y:12'的鼠標座標。你看到這些結果的瀏覽器是什麼? – robertc 2011-05-06 00:02:02

+0

谷歌瀏覽器10.0.648.204 – bsr 2011-05-06 00:50:36

+1

這可能只是一個瀏覽器錯誤,在11.0.696.57測試版中,我還得到了基於svg x:12 y:12'的鼠標座標。 – robertc 2011-05-06 01:12:48

回答