Javascript examples for Chart.js:Bar Chart
Set backgroundColor and borderColor barchart using Chart.js
<html lang="en"> <head> <title>Chart.js Configure Colors Dynamically</title> </head> <body translate="no"> <div style="width: 50%"> <canvas id="canvas"></canvas> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script> <script> randomScalingFactor = function() { return Math.round(Math.random() * 100); } function getData() {//from w w w . j ava 2s . c om var dataSize = 32; var evenBackgroundColor = 'rgba(255, 99, 132, 0.2)'; var evenBorderColor = 'rgba(255,99,132,1)'; var oddBackgroundColor = 'rgba(75, 192, 192, 0.2)'; var oddBorderColor = 'rgba(153, 102, 255, 1)'; var labels = []; var scoreData = { label: 'Mid-Term Exam 1', data: [], backgroundColor: [], borderColor: [], borderWidth: 1, hoverBackgroundColor: 'rgba(200, 200, 200, 1)', hoverBorderColor: 'rgba(200, 200, 200, 1)', }; for (var i = 0; i < dataSize; i++) { scoreData.data.push(window.randomScalingFactor()); labels.push("Score " + (i + 1)); if (i % 2 === 0) { scoreData.backgroundColor.push(evenBackgroundColor); scoreData.borderColor.push(evenBorderColor); } else { scoreData.backgroundColor.push(oddBackgroundColor); scoreData.borderColor.push(oddBorderColor); } } return { labels: labels, datasets: [scoreData], }; }; window.onload = function() { var chartData = getData(); console.dir(chartData); var myBar = new Chart(document.getElementById("canvas").getContext("2d"), { type: 'bar', data: chartData, options: { title:{ display: true, text: "Chart.js - Dynamically Data and Colors" }, legend: { display: false }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }; //# sourceURL=pen.js </script> </body> </html>