How to draw Circles in an Arc?

2020-03-30 05:22发布

问题:

I'm trying to make an arc and fill it with small circles, but I can't add circle in path tag.I have to draw 10 rows of circles inside an Arc that each row contains 10 circles.The circles should be like Tilford Tree,Visit http://bl.ocks.org/mbostock/4063550. Does anyone know what I'm doing wrong? This is my code:

 var w = 1200, h = 780,
 x = d3.scale.linear().range([0, w]),
 y =  d3.scale.linear().range([0, h]);

var svgContainer = d3.select("body").append("svg").attr("width",w)
                   .attr("height", h).attr("id", "svgBody").append("g");

var svgSector = d3.svg.arc().innerRadius(100).outerRadius(200)
            .startAngle(0.5 * Math.PI ).endAngle( Math.PI );

svgContainer.append("path").attr("d", svgSector)
              .attr("transform", "translate(600,0)")
              .append("circle").attr('r', 10);

回答1:

Paths are paths. Circles are circles. They are separate SVG elements. You can't mix them. You need to make a loop and calculate the centre of each of your circles using trigonometry.

var w = 1200, h = 780,
 x = d3.scale.linear().range([0, w]),
 y =  d3.scale.linear().range([0, h]);

var svgContainer = d3.select("body").append("svg").attr("width",w)
                   .attr("height", h).attr("id", "svgBody").append("g");

var arcradius = 100;
var circleradius = 10;

// Approx number of circles we can fit around the circumference
var n = (Math.PI * 2 * arcradius) / (2 * circleradius);

for (var i=0; i<10; i++)
{
  var ang = (Math.PI * 2 * i) / n;
  var cx = arcradius * Math.sin(ang);
  var cy = arcradius * Math.cos(ang);

  svgContainer.append("circle")
              .attr('cx', cx)
              .attr('cy', cy)
              .attr('r', circleradius)
              .attr("transform", "translate(300,300)");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>