如何获得SVG子元素的位置相对于SVG在页面上的位置,D3.js

How to get SVG child element position relative to SVG position on page, D3.js?

本文关键字:位置 SVG js D3 相对于 何获得 元素      更新时间:2023-09-26

我在SVG地图上有一个圆针。其中SVG位于div"location-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位置?

SVGCircle具有cxcy属性,分别代表centerX和centry。
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>