-2

有没有人使用 Chart.js 的最新版本 3.X 做过仪表图?

我见过有人在 2.X 版上修改甜甜圈图。

想知道是否有人用 3.X 做过,或者只是在寻找一些提示

4

1 回答 1

1

您可以使用插件核心 API,它提供了一系列可用于执行自定义代码的钩子。例如,afterDraw钩子可用于将针直接拉到canvas通孔上CanvasRenderingContext2D

请看下面的可运行代码,看看如何使用 Chart.js 版本 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>

于 2021-09-03T15:11:20.177 回答