Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

javascript - 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++) { %>'
+'<li>'
+'<span style="background-color:<%=datasets[i].lineColor%>"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'</li>'
+'<% } %>'
+'</ul>'

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) {
                console.log(chart.data);
                var text = [];
                text.push('<ul>');
                for (var i=0; i<chart.data.datasets[0].data.length; i++) {
                    text.push('<li>');
                    text.push('<span style="background-color:' + chart.data.datasets[0].backgroundColor[i] + '">' + chart.data.datasets[0].data[i] + '</span>');
                    if (chart.data.labels[i]) {
                        text.push(chart.data.labels[i]);
                    }
                    text.push('</li>');
                }
                text.push('</ul>');
                return text.join("");
            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you guys run through this post and tried the posted answer and didn't work, try this one:

  legendCallback: function(chart) {
    var text = [];
    text.push('<ul>');
    for (var i=0; i<chart.data.datasets.length; i++) {
      console.log(chart.data.datasets[i]); // see what's inside the obj.
      text.push('<li>');
      text.push('<span style="background-color:' + chart.data.datasets[i].borderColor + '">' + chart.data.datasets[i].label + '</span>');
      text.push('</li>');
    }
    text.push('</ul>');
    return text.join("");
  },

Then add this below:

document.getElementById('chart-legends').innerHTML = myChart.generateLegend();

To create the legends. Make sure you have an element <div id="chart-legends"></div>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...