-1

Has anyone done a gauge chart using the lattest version 3.X of Chart.js?

I've seen people modifying the Doughnut charts on the version 2.X.

Wondering if anyone has done it with 3.X or just looking for some tips

Andre Mendes
  • 11
  • 1
  • 3
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 07 '21 at 12:07

1 Answers1

2

You can use the Plugin Core API that offers a range of hooks that may be used for performing custom code. The afterDraw hook for example can be used to draw the needle directly on the canvas through CanvasRenderingContext2D.

Please take a look at below runnable code and see how it can be done with Chart.js version 3.

new Chart('myChart', {
  type: 'doughnut',
  plugins: [{
    afterDraw: chart => {
      var needleValue = chart.config.data.datasets[0].needleValue;
      var dataTotal = chart.config.data.datasets[0].data.reduce((a, b) => a + b, 0);
      var angle = Math.PI + (1 / dataTotal * needleValue * Math.PI);
      var ctx = chart.ctx;
      var cw = chart.canvas.offsetWidth;
      var ch = 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 - 20, 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();
    }
  }],
  data: {
    labels: [],
    datasets: [{
      data: [35, 35, 35],
      needleValue: 27,
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(63, 191, 63, 0.2)'
      ]
    }]
  },
  options: {
    responsive: false,
    aspectRatio: 2,
    layout: {
      padding: {
        bottom: 3
      }
    },
    rotation: -90,
    cutout: '50%',
    circumference: 180,
    legend: {
      display: false
    },
    animation: {
      animateRotate: false,
      animateScale: true
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart"></canvas>
uminder
  • 23,831
  • 5
  • 37
  • 72