Search code examples
javascriptpie-chart

JavaScript PieChart Slices - partially fill slices with color


Using JavaScript I am attempting to write a pie-chart to partially fill the slices with the color as a percentage of the slice area starting from the center of the circle. The code below is functioning correctly, but fills the whole of the slice with the color and I want to fill only a percentage using iNdx of ariFillPercent.

An example showing how to do that would be great.

const ariSizes = [120, 100, 140];
const arsColors = ["#FFDAB9", "#E6E6FA", "#E0FFFF"];
const ariFillPercent = [22, 32, 55];

  //==== FUNCTION ====//
  const handleDrawSegment = (cnv, ctx, iNdx) => {
    ctx.save();
    var centerX = Math.floor(cnv.width / 2);
    var centerY = Math.floor(cnv.height / 2);
    let radius = Math.floor(cnv.width / 2);

    var startingAngle = handleDegreesToRadians(handleSumTo(ariSizes, iNdx));
    var arcSize = handleDegreesToRadians(ariSizes[iNdx]);
    var endingAngle = startingAngle + arcSize;

    ctx.beginPath();
    ctx.moveTo(centerX, centerY);
    ctx.arc(centerX, centerY, radius,
      startingAngle, endingAngle, false);
    ctx.closePath();

    ctx.fillStyle = arsColors[iNdx];
    ctx.fill();

    ctx.restore();
  }


Solution

  • Rather than simply applying a proportion of the radius to represent the percentage, I think that it is better to calculate the radius from the relevant proportion of the area for the slice, because I think that this gives a better perspective of the size. When I have seen these types of pie-charts, all of the slices are the same size, and the size of the subject is determined by the amount of fill. This I presume is an alternative to using a bar chart.

    To calculate the radius used for the fill, I used the following code:

      const nArea = (Math.PI * (_nPieRadius * _nPieRadius)) *
        (ariFillPercent[iSlice] / 100);
      const nThisRadius = Math.sqrt(nArea / Math.PI);