如何为饼图添加动态颜色 - Chart JS

RAL*_*RAL 2 javascript colors chart.js angular

我有一个像这样的饼图:

this.canvas = document.getElementById('chart');
    this.ctx = this.canvas.getContext('2d');
    const myChart = new Chart(this.ctx, {
      type: 'pie',
      data: {
        labels: names,
        datasets: [{
          label: '# of dogs',
          data: data,
          backgroundColor: color???,
          borderWidth: 1
        }]
      },
      options: {
        responsive: false,
        display: true
      }
    });
Run Code Online (Sandbox Code Playgroud)

数据不是固定的数据。它是一个数组,可以包含不同的数据。如何使饼图的每一块都有不同的颜色?

谢谢!

小智 5

这是我的建议:第 1 步

colors=[];
Run Code Online (Sandbox Code Playgroud)

第2步

for(let i=0;i<this.data.length;i++){
      this.colors.push('#'+Math.floor(Math.random()*16777215).toString(16));
}
Run Code Online (Sandbox Code Playgroud)

步骤 3

data: data,
backgroundColor: this.colors
.....
Run Code Online (Sandbox Code Playgroud)