Chart.js Picture inside doughnut segment

后端 未结 1 856
时光取名叫无心
时光取名叫无心 2021-01-28 07:31

I found out about chart.js and I am looking to use a doughnut chart for my website, I found a example where I can take the basics from : https://jsfiddle.net/9wp4f693/2/

<
1条回答
  •  执笔经年
    2021-01-28 08:11

    There is no native ChartJS API for drawing an image inside a donut chart.

    But you can manually add the images after the chart has been drawn.

    For each wedge in the donut:

    Warning: untested code ... some tweaking might be required

    1. Translate inward to the middle of the donut.

      // calculate donut center (cx,cy) & translate to it
      var cx=chart.width/2;
      var cy=chart.height/2;
      context.translate(cx,cy);
      
    2. Rotate to the mid-angle of the target donut-wedge

      var startAngle = chart.segments[thisWedgeIndex].startAngle;
      var endAngle = chart.segments[thisWedgeIndex].endAngle;
      var midAngle = startAngle+(endAngle-startAngle)/2;
      
      // rotate by the midAngle
      context.rotate(midAngle);
      
    3. Translate outward to the midpoint of the target donut-wedge:

      // given the donut radius (innerRadius) and donut radius (radius)
      var midWedgeRadius=chart.innerRadius+(chart.radius-chart.innerRadius)/2;
      context.translate(midWedgeRadius,0);
      
    4. Draw the image offset by half the image width & height:

      // given the image width & height
      context.drawImage(theImage,-theImage.width/2,-theImage.height/2);
      
    5. Clean up the transformations by resetting the transform matrix to default:

      // undo translate & rotate
      context.setTransform(1,0,0,1,0,0);
      

    0 讨论(0)
提交回复
热议问题