How to put text into donut chart using react-chartjs-2.js?
P粉378264633
P粉378264633 2024-03-30 15:14:29
0
1
382

How to put text into a donut chart using react-chartjs-2.js and Typescript when the chart's title is at the top and the label is on the right side of the donut chart. The solutions I've found so far don't seem to work with side tags or React/TS.

This is what I have now:

...

setOptions({
   responsive: true,
   plugins: {
     legend: {
       position: 'right',
       rtl : true,
       labels: {
         usePointStyle: true,
         pointStyle: 'circle',
       }
     },
     title: {
       display: true,
       text: 'Title',
       font: {
         size: 25,
       }
     }
   },
});
    
setPlugins ({
    id: "tooltipLine",
    beforeDraw: function(chart) {
      var width = chart.width,
      height = chart.height,
      ctx = chart.ctx;
      ctx.restore();
      var fontSize = (height / 160).toFixed(2);
      ctx.font = fontSize + "em sans-serif";
      ctx.textBaseline = "top";
      var text = "Foo-bar",
      textX = Math.round((width - ctx.measureText(text).width) / 2),
      textY = height / 2;
      ctx.fillText(text, textX, textY);
      ctx.save();
    }
})
<Doughnut id="pieChart" data={data} options={options} plugins={[plugins] as any}/>

But this just makes the text in the middle of the entire canvas, not the middle of the donut.

P粉378264633
P粉378264633

reply all(1)
P粉872101673
const plugins = [{
        beforeDraw: function(chart) {
            var width = chart.width,
                height = chart.height,
                ctx = chart.ctx;
            ctx.restore();
            var fontSize = (height / 160).toFixed(2);
            ctx.font = fontSize + 'em sans-serif';
            ctx.textBaseline = 'top';

            // Draw "Total" on the first line
            var text1 = 'Total';
            var textX1 = Math.round((width - ctx.measureText(text1).width) / 2);
            var textY1 = height / 2.5;
            ctx.fillText(text1, textX1, textY1);

            // Draw the number on the second line
            var text2 = totalStatusCountRef.current;
            var textX2 = Math.round((width - ctx.measureText(text2).width) / 2);
            var textY2 = height / 1.9;
            ctx.fillText(text2, textX2, textY2);

            ctx.save();
        }
    }];
     
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!