我想知道如何获取圆的中心点来动态放置我的标记。在我的真实项目中,我的圆可以位于 svg 内的随机位置,并且我必须找到我的标记,以便其底部尖端位于圆的中心。
我该怎么做?
<body>
<script type="text/javascript">
const svg = d3.select("body").append("svg").attr("width",1000).attr("height",1000);
svg.append("circle").attr("r",5).attr("cx",100).attr("cy",200).style("stroke","#FF0000");
var widthMarker=50;
var img = svg.append("svg:image")
.attr("xlink:href", "marker.svg")
.attr("width", widthMarker)
.attr("height", widthMarker)
.attr("x", 228)
.attr("y",53)
</script>
</body>
最佳答案
首先,命名您的选择:
var circle = svg.append("circle")
.attr("r", 5)
.attr("cx", 100)
.attr("cy", 200)
.style("stroke", "#FF0000");
话虽这么说,回到你的问题:
首先,使用 getBBox()
获取圆的坐标(假设没有没有翻译),假设您出于某种原因不知道它的坐标位置(即,既不是其 cx
也不是其 cy
值):
var circleBox = circle.node().getBBox();
然后,使用这些坐标设置 x
和 y
位置:
.attr("x", circleBox.x + circleBox.width/2 - widthMarker/2)
.attr("y",circleBox.y + circleBox.height/2 - widthMarker)
这是更新后的 Plunker:http://plnkr.co/edit/DYlJsUhrF1OgoChq927L?p=preview
关于javascript - 如何使用d3.js获取圆心坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49524927/