Chartjs-How to show speedometer on Doughnut chart in chart.js using reactjs

0👍

Base on the code sample from Konstantin S., you could register a plugin globally inside the componentDidMount() method and implement an afterDraw function as follows:

componentDidMount() {
  Chart.pluginService.register({
    afterDraw: chart => {
      var needleValue = chart.chart.config.data.datasets[0].needleValue;
      var dataTotal = chart.chart.config.data.datasets[0].data.reduce((a, b) => a + b, 0);
      var angle = Math.PI + (1 / dataTotal * needleValue * Math.PI);
      var ctx = chart.chart.ctx;
      var cw = chart.chart.canvas.offsetWidth;
      var ch = chart.chart.canvas.offsetHeight;
      var cx = cw / 2;
      var cy = ch - 6;

      ctx.translate(cx, cy);
      ctx.rotate(angle);
      ctx.beginPath();
      ctx.moveTo(0, -3);
      ctx.lineTo(ch - 10, 0);
      ctx.lineTo(0, 3);
      ctx.fillStyle = 'rgb(0, 0, 0)';
      ctx.fill();
      ctx.rotate(-angle);
      ctx.translate(-cx, -cy);
      ctx.beginPath();
      ctx.arc(cx, cy, 5, 0, Math.PI * 2);
      ctx.fill();
    }
  });
}

This expects the property needleValue to be defined inside the dataset.

datasets: [{
  data: [500, 500, 500],
  needleValue: 580,
  ...
}],

Please have a look at your amended CodeSandbox

Leave a comment