javascript - 如何使用d3.js获取圆心坐标

标签 javascript d3.js

我想知道如何获取圆的中心点来动态放置我的标记。在我的真实项目中,我的圆可以位于 svg 内的随机位置,并且我必须找到我的标记,以便其底部尖端位于圆的中心。

enter image description here

我该怎么做?

  <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>

http://plnkr.co/edit/vFtJkZ1GKmyGYIUR0wXR?p=preview

最佳答案

首先,命名您的选择:

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();

然后,使用这些坐标设置 xy 位置:

.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/

相关文章:

javascript - NVD3.js 线图无法将 y 轴缩放到最大值和最小值

javascript - 如何使用COOKIES jquery仅加载一次DIV

javascript - Angularjs指令调用 Controller 函数

javascript - d3.js 404 json 文件未找到

javascript - 在 d3.js 中将鼠标悬停在 map 上时生成带有市镇名称的标题

javascript - 从 d3v4 更改为 d3v3 会使条形消失

javascript - mouseout 图像隐藏包含文本的 div

javascript - 调整 javascript 行

javascript - 创建 Ruby Gem 以将 HTML/JavaScript 插入主应用程序

javascript - 如何将数据表动态转换为树状json格式?