ChartJS v2.0的自定义图例 [英] Custom Legend with ChartJS v2.0
问题描述
我正在尝试在ChartJS v2.0中创建自定义图例模板。在ChartJS的v1 *中,我只是向新的Chart构造函数添加了一个属性,例如......
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>'
我似乎无法在v2.0中找到此选项的任何文档。它甚至可用吗?任何人都可以举例说明如何实现这一目标吗?
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?
谢谢!
更新 - 工作下面的代码
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("");
}
推荐答案
有一个 legendCallback
功能:
legendCallback 功能
function(chart){}
生成图例的功能。接收图表对象以生成图例。默认的
实现返回一个HTML字符串。
legendCallback Function
function (chart) { }
Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string.
详细信息可以在这里找到:
http://www.chartjs.org/docs/latest/configuration/legend.html# html-legends
例如(通过 - https: //github.com/chartjs/Chart.js/issues/5070)- 默认图例回调:
Details can be found here: http://www.chartjs.org/docs/latest/configuration/legend.html#html-legends For example (via - https://github.com/chartjs/Chart.js/issues/5070)- The default legend callback:
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('<li><span style="background-color:' +
chart.data.datasets[i].backgroundColor +
'"></span>');
if (chart.data.datasets[i].label) {
text.push(chart.data.datasets[i].label);
}
text.push('</li>');
}
text.push('</ul>');
return text.join('');
}
这篇关于ChartJS v2.0的自定义图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!