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.
-
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
2 Answers
Reset to default 4Using 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>