Applying background-color in bar chart using chart.js - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Applying background-color in bar chart using chart.js

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//from  w w w.j av  a2s .co m
var ctx = document.getElementById("myChart");
var randomColorPlugin = {
    beforeUpdate: function(chart) {
        var backgroundColor = [];
        var borderColor = [];
        for (var i = 0; i < chart.config.data.datasets[0].data.length; i++) {
           var color = "rgba(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ",";
            backgroundColor.push(color + "0.2)");
            borderColor.push(color + "1)");
        }
        chart.config.data.datasets[0].backgroundColor = backgroundColor;
        chart.config.data.datasets[0].borderColor = borderColor;
    }
};
Chart.pluginService.register(randomColorPlugin);
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["January", "February", "March", "April", "May", "June"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            borderColor: 'rgba(255,99,132,1)',
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart" height="200"></canvas>  
   </body>
</html>

Related Tutorials