AndFisher
AndFisher

Reputation: 643

Calculating a the length of an arc in D3

I am working with a sunburst graph in D3 and need to calculated the width of any given segment. In the below diagram how can I get the actual width in pixels of the line A-B for Arc1?

enter image description here

Upvotes: 0

Views: 751

Answers (1)

AndFisher
AndFisher

Reputation: 643

Presumably if I know the innerRadius for an arc (which will be the same length for A and B) I can plot an imaginary triangle and use the Law of Cosines

c2 = a2 + b2 - 2ab cos C

But I'd need the angle C. This be retrieved in D3 by getting the difference in start and end angles.

var x = d3.scaleLinear()
    .range([0, 2 * Math.PI])
    .clamp(true);

var y = d3.scaleLinear()
    .range([0, this.radius])
    .clamp(true);

var.arc = d3.arc()
    .startAngle(function(d) {
        return x(d.x0);
    })
    .endAngle(function(d) {
        return x(d.x1);
    });

function getRingRadius() {
    // for example
    return 50;
}

function measureSegment(d) {
    var a = getRingRadius() * (d.depth || 0), b = a;
    var C = arc.startAngle()(d) - arc.endAngle()(d);

    return Math.sqrt((a*a + b*b) - 2*a*b*Math.cos(C));
}

Upvotes: 2

Related Questions