如何更改 Chart.js 图表中文本的颜色

How to change the color of the text in the Chart.js chart

我使用 Chart.js 库创建图表及其 'chartjs-plugin-datalabels.js' 插件。我这里的问题是如何更改图表上值的颜色,因为我不能使用 CSS 样式,因为它被渲染为图像

尝试使用库 patternomaly

示例:

var ctx = document.getElementById('canvas').getContext('2d');

var chart = new Chart(ctx, {
  type: 'pie',
  data: {
    datasets: [{
      data: [45, 25, 20, 10],
      backgroundColor: [
        pattern.draw('square', '#ff6384'),
        pattern.draw('circle', '#36a2eb'),
        pattern.draw('diamond', '#cc65fe'),
        pattern.draw('triangle', '#ffce56')
      ]
    }],
    labels: ['Red', 'Blue', 'Purple', 'Yellow']
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/patternomaly@1.3.2/dist/patternomaly.min.js"></script>

<canvas id="canvas"></canvas>

文档: https://www.chartjs.org/docs/latest/general/colors.html

改变标签颜色就是first example in the plugin documentation.

下面是显示更改图表中所有数据集颜色的片段:

new Chart(document.getElementById("chart"), {
  type: "pie",
  data: {
    labels: ['a', 'b', 'c', 'd'],
    datasets: [{
      data: [1, 2, 4, 8]
    }]
  },
  options: {
    maintainAspectRatio: false,
    plugins: {
      datalabels: {
        color: 'red'
      }
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.1"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<canvas id="chart"></canvas>