Dave Maison
Dave Maison

Reputation: 417

JS doughnut chart w/ percentage out of order

I've burned too many hours on this, so I come to you.

I'm attempting to generate a user avatar that has an SVG doughnut surrounding it that denotes the completeness of their profile as a percent.

Easy.

Unfortunately, the design calls for the percentage label to appear outside the doughnut, at the end of the stroke.

Difficult.

I figured that since the center of the circle isn't at 0,0 like it would be in a graph, I could find the x and y coords by assuming the radius is the hypotenuse of a right angle triangle, and the sum of the legs and the radius would be equal to the respective coordinates, which appears to be true. I am successfully plotting an arc in this manner

However, something is really funky with my math and the percentages appear out of order.

This is my code:

 findPercentagePosition( percentage ){
    let q = 1,
    angle = ( percentage / 100 * 360 );

    const C = 90,
    A = angle,
    B = Math.abs( C - A ), 
    c = this.arc.radius, // hypotenuse
    a = Math.abs( c * Math.sin( A ) ), //r*sin( angle )
    b = Math.sqrt( Math.pow( c, 2 ) - Math.pow( a, 2 ) ), // b^2=c^2-a^2
    CENTER = c + this.arc.strokeWidth + this.arc.offset;

    return {
        x: b + CENTER,
        y: a + CENTER
    };
}

This is what happens when I try to render 0% to 24% enter image description here

Clearly I'm doing something correct(ish), because its generating an arc, but just not in the right order.

Upvotes: 1

Views: 54

Answers (1)

Barmar
Barmar

Reputation: 781706

The trigonometry functions work with radians, not degrees. A circle has 2π radians, not 360. So change it to:

const angle = percentage/100 * 2 * Math.PI;
const C = Math.PI/2;

Upvotes: 2

Related Questions