2013-06-20 150 views
0

如果任何人可以帮助我解决这个svg问题,我就会徘徊。如何获取svg对象的鼠标坐标版本。通常当用户点击页面时,点击事件就会触发,并且该对象具有x和y方向的鼠标位置。就我而言,我不想在事件中做到这一点。通过简单地检查svg对象的属性(如x和y坐标),可以获得鼠标位置吗?我整理了一个示例页面,希望它更清晰。 http://jsfiddle.net/kenny12/XBCHF/是链接。摘录如下:SVG到屏幕坐标

var svg = document.getElementsByTagName('svg')[0]; 
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(elem){ 
    elem.addEventListener('mousedown',function(e){ 
     log_mouseclick = "mouse clicked at"+ " x:" + e.clientX +" y:" + e.clientY ; 
     var svgmouse = svgcursorPoint(e);  
     log_mousecoord = "svg mouse at"+ " x:" + svgmouse.x +" y:" +svgmouse.y; 
     document.getElementById('op').innerHTML = log_svgcursorPoint + "<br>" + log_mouseclick + "<br>" + log_mousecoord; 
    },false); 
})(el1); 
(function calc_manually(){ 
    var rec = document.getElementsByTagName("rect")[0]; 
    var root = document.getElementsByTagName("svg")[0]; 
    var x = rec.getAttribute("x"); 
    var y = rec.getAttribute("y"); 
    var CTM = root.getScreenCTM(); 
// How to get the mouse position these information without using events is the problem. 
})(); 
+1

在位于其中一些除了0,0,其效果更好(HTTP:/ /stackoverflow.com/questions/2601097/how-to-get-the-mouse-position-without-events-without-moving-the-mouse)回答这是不可能的。但是有两个变量'mouseX'和'mouseY'并在每次鼠标移动时使用事件更新这些变量有什么问题?然后你可以在需要坐标时抓住这些变量。 – basilikum

+0

这不是我的情况,我需要计算一个svg对象的屏幕坐标。假设我在svg坐标系中有一个“5”作为对象。如何从坐标转换到屏幕坐标是我的问题。 –

回答

4

为什么你不想要一个事件?这就是他们的目的。如果您正在处理鼠标坐标,只需在对象上粘贴标准DOM事件侦听器,然后在触发时,使用屏幕上元素位置的event.target.getBoundingClientRect()函数以及event.offsetX/screenX和event.offsetY/screenY属性为鼠标坐标。

简单示范:http://jsfiddle.net/HBmYV/1/

+0

由于某些原因,offsetX或Y在FireFox或Chrome中不起作用。有理由吗? –

+0

有点困惑,如果'event.target.getBoundingClientRect()'返回rect对象而不是svg对象。 –

+0

offsetX/Y是相对于元素(0,0)的鼠标坐标。 IE9和IE10也应该支持这些。 getBoundingClientRect()+元素的(0,0)会给你绝对位置 –

0

可以使用事件层,以及如果svg元素根据[此]的页面p.x =event.layerX || event.clientX;