【问题标题】:How to get SVG child element position relative to SVG position on page, D3.js?如何获取 SVG 子元素位置相对于页面上的 SVG 位置,D3.js?
【发布时间】:2015-10-01 12:35:53
【问题描述】:

我在 SVG 地图上有一个圆形图钉。 SVG位于带有溢出的div“位置图”内:隐藏。 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 位置?

【问题讨论】:

    标签: javascript d3.js svg


    【解决方案1】:

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

    【讨论】:

    • 有了这个我得到这个错误“Uncaught TypeError: Cannot read property 'getAttribute' of null_a.attr @ d3.min.js:3(anonymous function)”。我正在使用这个版本。 cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js
    • 嗯,你没有得到圈子,尝试做d3.selectAll('.pin').append('circle', '.pin').select('circle').attr()
    猜你喜欢
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多