Chartjs-How can I get chart.js to automatically add colours for dynamic labels?

1๐Ÿ‘

โœ…

If you push the values to an array imidiatly instead of to a string it will work fine.

Example:

function getRandomColor() { //generates random colours and puts them in string
  var colors = [];
  for (var i = 0; i < 3; i++) {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var x = 0; x < 6; x++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    colors.push(color);
  }
  return colors;
}

const data = {
  labels: [
    'Red',
    'Blue',
    'Yellow'
  ],
  datasets: [{
    label: 'My First Dataset',
    data: [300, 50, 100],
    backgroundColor: getRandomColor(),
    hoverOffset: 4
  }]
};

const options = {
  type: 'pie',
  data
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Leave a comment