[Chartjs]-Why are the default Chart.js legend boxes transparent rectangles?

6👍

This is because you haven’t set the backgroundColor property for your datasets (which is responsible for the legend­‘s fill color).

datasets: [{
   backgroundColor: "#3e95cd",
   borderColor: "#3e95cd",
   data: [10943, 29649, 6444, 2330, 36694],
   fill: false,
   borderWidth: 2
}, {
   backgroundColor: "#ff3300",
   borderColor: "#ff3300",
   data: [9283, 1251, 6416, 2374, 9182],
   fill: false,
   borderWidth: 2
}]

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var barChartData = {
   labels: ["2013-03-09", "2013-03-16", "2013-03-23", "2013-03-30", "2013-04-06"],
   datasets: [{
      backgroundColor: "#3e95cd",
      borderColor: "#3e95cd",
      data: [10943, 29649, 6444, 2330, 36694],
      fill: false,
      borderWidth: 2
   }, {
      backgroundColor: "#ff3300",
      borderColor: "#ff3300",
      data: [9283, 1251, 6416, 2374, 9182],
      fill: false,
      borderWidth: 2
   }]
};

Chart.defaults.global.defaultFontFamily = "'Comic Sans MS'";
// Disable pointers
Chart.defaults.global.elements.point.radius = 0;
Chart.defaults.global.elements.point.hoverRadius = 0;

var ctx = document.getElementById("bar-chart").getContext("2d");
new Chart(ctx, {
   type: 'line',
   data: barChartData,
   options: {
      responsive: true,
      legend: {
         display: true,
         position: "right"
      },
      title: {
         display: false
      },
      scales: {
         xAxes: [{
            type: "time",
            ticks: {
               minRotation: 90
            }
         }]
      }
   }
});
<script src="http://www.chartjs.org/dist/master/Chart.bundle.min.js"></script>
<canvas id="bar-chart"></canvas>

Leave a comment