开发者

JavaScript: How to get the center of a pie slice?

Hi I am trying to create a simple pie chart using the HTML canvas element. I found a nice tutorial on the web and starting to learn how it is done.

Now I want to add some text and I need to know how to find the center of each slice in the pie where the text can be added.

Here is the loop code:

    for ( i = 0; i < t.data.length; i++ )
    {
        label = t.data[i].label;
        value = t.data[i].value;
        color = t.data[i].color;

        ctx.lineWidth = t.strokeLineWidth;
        ctx.strokeStyle = "#FFFFFF";
        ctx.fillStyle = color;

        ctx.beginPath();
        ctx.moveTo( centerX, centerY );
        ct开发者_JAVA百科x.arc( centerX, centerY, radius, lastEnd, lastEnd + ( Math.PI * 2 * ( value / total ) ), false );
        ctx.lineTo( centerX, centerY );
        ctx.fill();
        ctx.stroke();

        lastEnd += Math.PI * 2 * ( value / total );
    }


Simply treat the slices as triangles, i.e. ignore the arc.

There are a bunch of different ways to define "the center". Have a look at the wikipedia article on how to do this. You'll probably want the intersection of the angle bisectors, which is called the incenter. This is the center of the inscribed circle, and it gives the most space for text.

The coordinates of the incenter is calculated as follows:

Let (xa,ya), (xb,yb), and (xc,yc) be the coordinates of the three corners of the triangle, and let a, b, and c be the lengths of the opposing sides. I.e., a = ||(xb,yb)-(xc,yc)||, etc. Finally, let P=a+b+c. Then the center is

((a xa + b xb + c xc)/P, (a ya + b yb + c yc)/P).

Cheers,


The math is more complicated than I can do quickly. You might try the rgraph library. http://www.rgraph.net/docs/pie.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜