[Chartjs]-How to put dynamic colors for pie chart – chart js

5👍

this is my suggestion :
Step 1

colors=[];

Step 2

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

Stap 3

data: data,
backgroundColor: this.colors
.....

3👍

Generate a random color

 function getRandomColor() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

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: getRandomColor(),
          borderWidth: 1
        }]
      },
      options: {
        responsive: false,
        display: true
      }
    });

Leave a comment