Phil Phil - 2 years ago 3829
Javascript Question

Custom Legend with ChartJS v2.0

I'm trying to create a custom legend template in ChartJS v2.0. In v1* of ChartJS I simply added a property to the new Chart constructor such as...

legendTemplate : '<ul>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'<% } %>'

I can't seem to find any documentation in v2.0 for this option. Is it even available anymore? Can anyone show an example of how to accomplish this?

Thank you!

Update - Working code below

legendCallback: function(chart) {
var text = [];
for (var i=0; i<[0].data.length; i++) {
text.push('<span style="background-color:' +[0].backgroundColor[i] + '">' +[0].data[i] + '</span>');
if ([i]) {
return text.join("");

Answer Source

There is a legendCallback function:

legendCallback Function function (chart) { }
Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string.

Details can be found here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download