Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw arc with d3.js with only outer radius, or sector of circle?

Tags:

svg

d3.js

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

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

this make path from A point to B and back to A. What should I use to draw simple arc from A to B? In the end this will be the line defined startAngle, endAngle and radius

like image 781
Raf Avatar asked Jul 15 '17 16:07

Raf


1 Answers

Unfortunately, there is no native D3 generator to create an arc the way you described in your question. You can write your own function to draw a circular arc, of course, nothing forbids you.

However, if you want to stick with D3 arc generator, you have a couple of alternatives.

The first one, very easy indeed, is just passing the same value for outerRadius and innerRadius. For instance, 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>

You may argue that "the arc is actually going and coming back in the same position, and that's not a true arc", as you stated in your question ("from A point to B and back to A"). Well, for modern browsers that makes absolutely no difference.

But if you really want this nano-micro-optimisation, you can get only the first M and A commands of the path, no matter what is the innerRadius:

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

Here is the 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>
like image 52
Gerardo Furtado Avatar answered Oct 09 '22 03:10

Gerardo Furtado