Search code examples
htmlcanvaschartstrigonometry

Is there a way to determine whether there's a sufficient amount of space in a Pie chart segment for a label?


In the attached Google charts Pie chart the labels fit well inside the segments. Determining the length of a bit of text in HTML5 canvas is easy enough - but how do you determine whether the label will fit into a particular segment (using trigonometry) ? As you can see on the image, two of the segments don't have labels inside the segment.

enter image description here

EDIT: Here's an example of what I have at the moment: https://www.rgraph.net/tests/canvas.pie/in-pie-labels.html

As you see the labels for the small segments overlap. What I'm after is a way to calculate whether there's enough space for the labels at the point where they're going to be rendered. If not, I can just not draw the label like in the example image above.

Could chord size be useful to do this?

Here's the forumulae for the chord size that I found via Google:

"Chord length using trigonometry = 2 × r × sin(θ/2); where 'r' is the radius of the circle and 'θ' is the angle subtended at the center by the chord."


Solution

  • I sorted it (in about one hour) after 3 days of trying to calculate it with trig by using the built-in context.isPointInPath() function...

    1. Draw the text (transparent color) to get the coordinates (x/y/w/h) of it. You might be able to get away with measuring it to get the width and height.
    2. Draw the segment in a transparent color and do not stroke or fill it. Also, do not close the path.
    3. Test each corner of the text rectangle (formed the x/y/w/h that you got above) using the context.isPointInPath() function. If the function returns true for each corner of the rectangle formed by the coordinates of the text, then the text will fit into the segment.