首页 > 解决方案 > 使用 D3 并通过附加 SVG 绘制两个圆圈

问题描述

我正在尝试使用 D3 并附加 SVG 来绘制两个圆圈。下面提供的代码没有产生预期的结果。它绘制了第一个绿色圆圈,但没有绘制下一个。请帮助我了解下面提供的代码有什么问题...

   <!DOCTYPE HTML>
    <html>
    <head>
    <title>Selection Method
    </title>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    </head>
    <body>
    <script>
    d3.select("body")
      .append("svg")
        .attr("width", 960)
        .attr("height", 500)
        .style('background', '#dff0d8')
      .append("g")
        .attr("transform", "translate(0,0)")
      .append("circle")
        .attr("cx", 20)
        .attr("cy", 20)
        .attr("r", 10)
        .attr("fill", "green")
    .append("circle")
        .attr("cx", 70)
        .attr("cy", 70)
        .attr("r", 10)
        .attr("fill", "black") 
    </script>
    </body>

标签: d3.jssvg

解决方案


您的代码尝试将第二个附加circle到第一个circle. 简单地“突出”代码不会改变范围。

这是一个微不足道的更改,可以得出您可能期望的结果:

d3.select("body")
  .append("svg")
    .attr("width", 960)
    .attr("height", 500)
    .style('background', '#dff0d8')
  .append("g")
    .attr("transform", "translate(0,0)")
  .append("circle")
    .attr("cx", 20)
    .attr("cy", 20)
    .attr("r", 10)
    .attr("fill", "green")
d3.select('g')  // <- Note the reselection of the existing 'g' element
    .append("circle")
    .attr("cx", 70)
    .attr("cy", 70)
    .attr("r", 10)
    .attr("fill", "black") 
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>


推荐阅读