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.
-
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>
本文标签: javascriptGet coordinates of element relative to enclosing svgStack Overflow
版权声明:本文标题:javascript - Get coordinates of element relative to enclosing svg - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1743989133a2514396.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论