Chart.js Legend Customization
legendCallback
method can be used to manipulate how legend's labels are generated. so, using this you can customize legend's box-color as well (such as, using datasets border-color instead of background-color), like so :
legendCallback: function(chart) {
var ul = document.createElement('ul');
var borderColor = chart.data.datasets[0].borderColor;
chart.data.labels.forEach(function(label, index) {
ul.innerHTML += `
<li>
<span style="background-color: ${borderColor[index]}"></span>
${label}
</li>
`; // ^ ES6 Template String
});
return ul.outerHTML;
}
ᴅᴇᴍᴏ ⧩
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [{
data: [1, 1, 1],
backgroundColor: 'rgba(0, 0, 0, 0)',
borderColor: ['#ff9800', '#e91e63', '#2196f3']
}]
},
options: {
responsive: false,
legend: false,
legendCallback: function(chart) {
var ul = document.createElement('ul');
var borderColor = chart.data.datasets[0].borderColor;
chart.data.labels.forEach(function(label, index) {
ul.innerHTML += `
<li>
<span style="background-color: ${borderColor[index]}"></span>
${label}
</li>
`; // ^ ES6 Template String
});
return ul.outerHTML;
}
}
});
legend.innerHTML = chart.generateLegend();
.chart-container {
display: flex;
}
#legend ul {
list-style: none;
font: 12px Verdana;
white-space: nowrap;
}
#legend li span {
width: 36px;
height: 12px;
display: inline-block;
margin: 0 5px 8px 0;
vertical-align: -9.4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<div class="chart-container">
<canvas id="ctx"></canvas>
<div id="legend"></div>
</div>