Chartjs-Chart.js displaying the text in center of the doughnut chart

0👍

You are defining your custom plugin in the wrong place of chart configuration.

It should:

  1. remove plugins from options if your plugin doesn’t need any config
  2. add plugin implementation to plugins filed of Doughnut tag(component)

Code

  const options = {
    responsive:true,
    cutout:'80%',
    layout:{
      padding:20,
    },
    borderWidth:'',
    plugins: {
    },
  };
  const myPlugin = {
      id: 'myPlugin',
      beforeDraw: (chart) => {
        const ctx = chart.ctx;
        const xCoor = chart.chartArea.left + (chart.chartArea.right - chart.chartArea.left) / 2;
        const yCoor = chart.chartArea.top + (chart.chartArea.bottom - chart.chartArea.top) / 2;
        ctx.save();
        ctx.font = 'bolder 24px';
        ctx.fillStyle = 'red';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(`${input1}`, xCoor, yCoor);
        ctx.restore();
      },
  }
  ........
   
  <Doughnut data={data} options={options} plugins:{[myPlugin]} />

Leave a comment