使用 ChartJS v2.0 自定义图例自定义、图例、ChartJS

2023-09-08 08:56:33 作者:淺憶︿夢微涼

我正在尝试在 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 函数 函数(图表){ }生成图例的函数.接收要从中生成图例的图表对象.默认实现返回一个 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.

详情可以在这里找到

查看此问题以获取默认图例回调:

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(''); 
}