Odoug4
Odoug4

Reputation: 80

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

I'm currently trying to get chart.js 2.0 to automatically generate new colours for dynamic labels. the use case is I'm making a pie chart using data from a database where each row is a new label and the count next to it is the data e.g. MOVIE | VOTES PER MOVIE. however, the problem with this is that I don't know how many rows there will be and therefore can't manually put in colours. I figured a solution may be to automatically generate colours and then use a for loop to insert them in. This is my code:

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)];
   }
   color = "'"+color+"'"+",";
   colors += color;
  }
  colors = colors.slice(0, -1);
  console.log(colors);
  return colors;
 }

const data = {
  labels: [
    'Red',
    'Blue',
    'Yellow'
  ],
  datasets: [{
    label: 'My First Dataset',
    data: [300, 50, 100],
    backgroundColor: [
        getRandomColor() // calls for 3 random colours 
        // e.g. returns '#DDA597','#A95647','#78366A'
    ],
    hoverOffset: 4
  }]
};

I've noticed that the commas separating them are part of the string so they don't properly separate the colours. However, I can't think of a way around this. Does anyone know of a possible solution to this. Or even a better approach to this problem.

Thanks in advance!

Upvotes: 1

Views: 3601

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31351

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>

Upvotes: 3

Related Questions