为什么点击坐标不是我所期望的?

时间:2014-03-29 05:29:39

标签: javascript svg raphael

为什么当我点击拉斐尔路径元素的开头或结尾时,坐标不是我所期望的?请参见示例(http://jsfiddle.net/gharabed/prh2J/1/

example中,我有一条从(10,10)到(100,100)的路径。如果我点击100,100附近的路径的最尖端,我会得到类似(107,108)的点击事件坐标。我距离线的末端不超过4或5个像素。实际上看起来我只有2个(最多可能是3个)像素。看起来坐标有点偏差。我在这里不考虑什么吗?

function sendAlert(e) {
    alert("Clicked at: " + e.x + "," + e.y + "   I would expect it to be near the coordinates in the path defined (10,10) or (100,100)");
}

var paper = Raphael(document.getElementById('myid'),200,200);
var line = paper.path('M10,10L100,100');
line.attr({"stroke":"red","stroke-width":4});
line.click(sendAlert);
alert("Click as close as you can to the end of either end of the line segment.")

1 个答案:

答案 0 :(得分:0)

我同意瓦西里所说的话。我做了一个小实用功能,它会给你准确的坐标。只需将mousedown事件传递给此函数。 (在sendalert函数中调用此函数)

(我正在使用javascript)。

var mainsvg = document.getElementsByTagName('svg')[0];

    function getSvgCordinates(event) {
                var m = mainsvg.getScreenCTM();
                var p = mainsvg.createSVGPoint();
                var x, y;

                x = event.pageX;
                y = event.pageY;

                p.x = x;
                p.y = y;
                p = p.matrixTransform(m.inverse());

                x = p.x;
                y = p.y;

                x = parseFloat(x.toFixed(3));
                y = parseFloat(y.toFixed(3));

                return {x: x, y: y};
            }