如何获得相对于持有onclick侦听器的SVG元素的点击坐标? [英] How to get the click coordinates relative to SVG element holding the onclick listener?

查看:91
本文介绍了如何获得相对于持有onclick侦听器的SVG元素的点击坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法计算相对于触发事件的元素的点击坐标(x和y).我还没有在网上找到一个简单的例子.

I haven't been able to calculate the click coordinates (x and y) relative to the element triggering the event. I have not found an easy example online.

我在HTML页面中有一个简单的svg(左边距为100px).它包含一个group(翻译后的30px 30px),其中附加了onclick侦听器.在group里面,我有一个宽度和高度均为50px的rect.

I have a simple svg (with 100px left margin) in an HTML page. It contains a group (translated 30px 30px) which has an onclick listener attached. And inside that group I have a rect with 50px width and height.

单击group元素的任何部分后,我将获得一个事件对象,该对象具有相对于HTML页面(evt.clientXevt.clientY)的坐标.

After I click any part of the group element, I get an event object with coordinates relative to the HTML page (evt.clientX and evt.clientY).

我需要知道的是用户在group元素(包含onclick侦听器的元素)内确切单击的位置.

What I need to know is where exactly the user clicked inside the group element (the element holding the onclick listener).

如何将clientXclientY坐标转换为group元素坐标.这么说,如果我单击rect的最左上部分,它应该给我x = 0和y = 0.

How do I convert clientX and clientY coordinates to the group element coordinates. So say, if I click the top leftmost part of the rect it should give me x=0 and y=0.

这是我目前拥有的:

<!DOCTYPE html>
<html>
    <head>
        <style>
            body{
                background:black;
            }
            svg{
                fill:white;
                background:white;
                position: absolute;
                top:100px;
                left:100px;
            }
            
        </style>
        <script>
            function clicked(evt){
                alert("x: "+evt.clientX+" y:"+evt.clientY);
            }
        </script>
    </head>
    <body>
        <div>
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200">
                <g transform="translate(30 30)" onclick="clicked(evt)">
                    <rect x="0" y="0" width="50" height="50" fill="red"/>
                </g>
            </svg>      
        </div>
    </body>
</html>

推荐答案

尝试使用getBoundingClientRect(): http://jsfiddle.net/fLo4uatw /

function clicked(evt){
    var e = evt.target;
    var dim = e.getBoundingClientRect();
    var x = evt.clientX - dim.left;
    var y = evt.clientY - dim.top;
    alert("x: "+x+" y:"+y);
}  

这篇关于如何获得相对于持有onclick侦听器的SVG元素的点击坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆