Chartjs-Chart.js random rgb background color generator not working

2👍

Change how you’re incrementing i in your while loop:

while (i <= internalDataLength) {
  ...    
  i++;
};

NB: there’s a chart library error in the following snippet, but the colours are now showing

var ctx = document.getElementById("centerPie");

var internalData = [300, 50, 100, 75];

var graphColors = [];
var graphOutlines = [];
var hoverColor = [];

var internalDataLength = internalData.length;
i = 0;
while (i <= internalDataLength) {
    var randomR = Math.floor((Math.random() * 130) + 100);
    var randomG = Math.floor((Math.random() * 130) + 100);
    var randomB = Math.floor((Math.random() * 130) + 100);
  
    var graphBackground = "rgb(" 
            + randomR + ", " 
            + randomG + ", " 
            + randomB + ")";
    graphColors.push(graphBackground);
    
    var graphOutline = "rgb(" 
            + (randomR - 80) + ", " 
            + (randomG - 80) + ", " 
            + (randomB - 80) + ")";
    graphOutlines.push(graphOutline);
    
    var hoverColors = "rgb(" 
            + (randomR + 25) + ", " 
            + (randomG + 25) + ", " 
            + (randomB + 25) + ")";
    hoverColor.push(hoverColors);
    
  i++;
};


var data = {
    labels: [
        "one",
        "two",
        "three",
        "four"
    ],
    datasets: [{
            data: [300, 50, 100, 75],
            backgroundColor: graphColors,
            hoverBackgroundColor: hoverColor,
            borderColor: graphOutlines
    }]
};

var options = {
    cutoutPercentage: 25,
    responsive: true
    
};



var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: data,
    options: options,
    animation: {
        animateRotate:true
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>

<div class="app container-fluid">
  <div id="header-holder"></div>
  <div class="row top-body">
    <div class='col-xs-12 col-md-6'>
      <canvas id="centerPie" width="10" height="10"></canvas>
    </div>
  </div>
</div>

Leave a comment