How to draw an arc with d3.js only outside radius or a sector of a circle?

To draw an arc with d3.js, we need to use the function

d3.arc()
  .innerRadius(..)
  .outerRadius(..)
  ...

      

make the path from A to B and back to A . What should I use to draw a simple arc from A to B ? At the end it will be the line startAngle , endAngle and the radius

+3


source to share


1 answer


Unfortunately, there is no built-in D3 generator to create the arc as you described in your question. You can write your own function to draw a circular arc, of course you are not prohibited from doing anything.

However, if you want to stick with the D3 arc generator, you have several alternatives.

The first, very simple, simply passes the same value for outerRadius

and innerRadius

. For example, a circular arc starting at 0 degrees and ending at 90 degrees:

var svg = d3.select("svg")
.append("g")
.attr("transform", "translate(150,75)");

var arc = d3.arc()
  .innerRadius(50)
  .outerRadius(50);
  
var sector = svg.append("path")
  .attr("fill", "none")
  .attr("stroke-width", 3)
  .attr("stroke", "darkslategray")
  .attr("d", arc({startAngle:0, endAngle:(Math.PI/2)}))
      

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
      

Run code


You can argue that "the arc does indeed go and return in the same position and it is not a true arc" as you said in your question ("from point A to B and back to A"). Well, for modern browsers, it absolutely doesn't matter.



But if you really want this nano-micro-optimization, you can only get the first commands M

and A

paths, no matter what is innerRadius

:

var myString = arc({startAngle: 0, endAngle: (Math.PI / 2)}).split(/[A-Z]/);
sector.attr("d", "M" + myString[1] + "A" + myString[2])

      

Here's a demo:

var svg = d3.select("svg")
  .append("g")
  .attr("transform", "translate(150,75)");

var arc = d3.arc()
  .innerRadius(0)
  .outerRadius(50);

var myString = arc({
  startAngle: 0,
  endAngle: (Math.PI / 2)
}).split(/[A-Z]/);

var sector = svg.append("path")
  .attr("fill", "none")
  .attr("stroke-width", 3)
  .attr("stroke", "darkslategray")
  .attr("d", "M" + myString[1] + "A" + myString[2])
      

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
      

Run code


+3


source







All Articles