最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get coordinates of element relative to enclosing svg - Stack Overflow

programmeradmin1浏览0评论

I have an SVG with elements and groups of elements in it. I want to get the coordinates of an enclosed element, relative to the outer SVG. Currently I am using document.getElementById(elementid).getBBox().y, which always returns 0.

I have an SVG with elements and groups of elements in it. I want to get the coordinates of an enclosed element, relative to the outer SVG. Currently I am using document.getElementById(elementid).getBBox().y, which always returns 0.

Share Improve this question edited Mar 19, 2016 at 20:01 altocumulus 21.6k13 gold badges64 silver badges86 bronze badges asked Mar 19, 2016 at 14:58 chri_chrichri_chri 3104 silver badges12 bronze badges 1
  • 1 getBBox will not take into account any transforms on the element or parent elements. I believe you want to use getBoundingClientRect – Mark Commented Mar 19, 2016 at 15:37
Add a ment  | 

2 Answers 2

Reset to default 4

Using jQuery you do it like this: var offset=svg.offset() (gives you the absolute position of the svg) and then var pos=elem.offset() which gives you the absolute position of your element. Substract one from the other. Here svg is jQuery('svg') and maybe elem is jQuery('#idOfElement') for example.

I am too lazy to do the vanilla JS bit, and also I would not remend using it. jQuery is attempting to be cross-browser and offset works very well on all browser implementations.

Also, you could try to leverage the browser positional system and set the position of the svg as 'relative', then elem.position() will give you the position relative to the first absolute parent element that has position relative or absolute.

.svg { position: relative } or $('svg').css({position:'relative'})

Then $('#myElemId').position() gives you the coordinates.

As I said in my ment, you can use getBoundingClientRect for this:

<!DOCTYPE html>
<html>

  <head>
  </head>

  <body>
    <svg width="500" height="500">
      <g transform="translate(100,100)rotate(45)">
        <text id="myText" x="10" y="10" style="fill:red">Hi Mom!</text>
      </g>
    </svg>
    <script>
      var rect = document.getElementById("myText").getBoundingClientRect();
      console.log("position is " + rect.top + "," + rect.left);
    </script>
  </body>

</html>

发布评论

评论列表(0)

  1. 暂无评论