gpt4 book ai didi

javascript - 如何获取相对于页面上 SVG 位置的 SVG 子元素位置,D3.js?

转载 作者:行者123 更新时间:2023-11-28 06:52:00 24 4
gpt4 key购买 nike

我在 SVG map 上有一个圆形图钉。 SVG 位于带有溢出:隐藏的 div“位置 map ”内。 SVG 尺寸大于 div 尺寸。

<div class="location-map">
<svg></svg>
</div>

svg.selectAll(".pin")
.data(places)
.enter().append("circle", ".pin")
.attr("r", 5)
.attr("fill", "#fff")
.attr("transform", function(d) {
return "translate(" + projection([
d.location.longitude,
d.location.latitude
]) + ")";
});

我想获取 SVG 上的圆形图钉位置,以便我可以在 div 内以负边距重新定位 SVG,以使圆形图钉在 div 上水平和垂直居中显示。

如何获取圆针的 x、y 位置?

最佳答案

SVGCirclecxcy属性,分别代表centerX和centerY。
d3 的 .attr() 方法也允许获取这些。

var circle = d3.selectAll(".pin");
var x = circle.attr('cx');
var y = circle.attr('cy');

snippet.log('x: '+x);
snippet.log('y: '+y)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<div class="location-map">
<svg>
<circle class="pin" cx="50" cy="50" r="25"/>
</svg>
</div>

关于javascript - 如何获取相对于页面上 SVG 位置的 SVG 子元素位置,D3.js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32879128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com