views:

69

answers:

2

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 since I am pretty retarded at math/geometry 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 );
        ctx.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 );
    }

Thanks in advance for sugestions and answers Kai

A: 

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

EddieC
+1  A: 

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,

James