dagda1
dagda1

Reputation: 28780

draw arc from 0 to 360 degrees with d3.js

YOu can see a working example of this here.

My questions is about the small inner blue arc. I want to show the arc starting at 0 and going to hypotenuse from 0 to 360.

At the moment m code looks like this that adds the arc:

const hypotenuseCoords = {
  x1: hypotenuseCentre,
  y1: parseFloat(state.hypotenuse.attr('y1')),
  x2: xTo,
  y2: dy
};

const angle = Math.atan2(hypotenuseCoords.y2 - hypotenuseCoords.y1, hypotenuseCoords.x2 - hypotenuseCoords.x1);

const arc = d3.svg.arc()
        .innerRadius(15)
        .outerRadius(20)
        .startAngle(Math.PI/2)
        .endAngle(angle + Math.PI/2);

state.innerAngle
  .attr('d', arc)
  .attr('transform', `translate(${hypotenuseCentre}, 0)`);

The problem is that the arc only goes from 0 to pi or 180 and from 180 to 360. I think the startAngle in my coordinates is wrong.

How can I get the arc to stretch right round from 0 to 360?

Upvotes: 2

Views: 1116

Answers (1)

wdickerson
wdickerson

Reputation: 869

After you calculate angle, try:

if(angle>0)
    angle = -2*(Math.PI) + angle;

If my trig is right :)

Update: Play with this fiddle to see the issue: http://jsfiddle.net/rcb94j8m/

atan2() was behaving fine for rays in quadrants 1 and 2, but was giving you trouble in quadrants 3 and 4. The -2*(Math.PI) shift gets you to the same ray, but going the other direction. Some studying of sign conventions with atan2() and d3.svg.arc() would probably lead you to a better explanation. I would be interested to read your conclusions, if you post them here.

Upvotes: 3

Related Questions