admin 管理员组

文章数量: 1086019

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>

本文标签: javascriptGet coordinates of element relative to enclosing svgStack Overflow