Chartjs-How to use same backgroundcolors out of an array to unknown data in chartjs?

0👍

First you define the data and color arrays outside of the chart configuration. Then you can generate the new arrays with repeating colors using the following function:

function repeatColors(data, colors) {
  var result = [];
  for (var i = 0; i < data.length; i++) {
    result.push(colors[i % colors.length]);
  }
  return result;
}

Please have a look at the following code sample:

var labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'];
var data = [8, 7, 5, 4, 3, 6, 2, 5, 7, 3, 8, 4, 6];
var bgColors = [
  "rgba(255, 159, 64, 0.2)", //orange
  "rgba(255, 205, 86, 0.2)", //yellow
  "rgba(75, 192, 192, 0.2)", // green
  "rgba(54, 162, 235, 0.2)", // blue
  "rgba(153, 102, 255, 0.2)" //purple
];
var borderColors = [
  "rgb(255, 159, 64)", //orange
  "rgb(255, 205, 86)", //yellow
  "rgb(75, 192, 192)", //green
  "rgb(54, 162, 235)", //blue
  "rgb(153, 102, 255)" //purple
];
var hoverBgColors = [
  "rgba(255, 159, 64, 0.4)", //orange
  "rgba(255, 205, 86, 0.4)", //yellow
  "rgba(75, 192, 192, 0.4)", // green
  "rgba(54, 162, 235, 0.4)", // blue
  "rgba(153, 102, 255, 0.4)" //purple    
];

function repeatColors(data, colors) {
  var result = [];
  for (var i = 0; i < data.length; i++) {
    result.push(colors[i % colors.length]);
  }
  return result;
}

new Chart(document.getElementById('canvas'), {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      data: data,
      backgroundColor: repeatColors(data, bgColors),
      borderColor: repeatColors(data, borderColors),
      borderWidth: 2,
      hoverBackgroundColor: repeatColors(data, hoverBgColors)
    }]
  },
  options: {
    responsive: true,
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" height="80"></canvas>

0👍

I used the ajax request wrongly. So I could not identify the length of the data coming from the request.
I solved it like this:

$.post("some_file.php", '', function(data) {
    iDependOnMyParameter(data);
});

function iDependOnMyParameter(param) {
    // You should do your work here that depends on the result of the request!
    alert(param)
}

Leave a comment