Custom Legend in Chart.js 2.1.3

吃可爱长大的小学妹 提交于 2019-12-12 17:14:47

问题


Is there a way to move and manipulate the legend in the Pie chart for Chart.js? Specifically I want to move it to the left or right of my pie chart and have it in a list-style instead of inline. I see in the documentation that the only positions are top or bottom so I tried hiding the default legend with

Chart.defaults.global.legend.display = false;

And then building my own with

document.getElementById('js-legend').innerHTML = myChart.generateLegend();

But this doesn't generate the colored legend boxes that correspond with the chart.

current javascript:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels:generatedLabels,
        datasets: [{
            data: dataPoints,
            backgroundColor: generatedBackgroundColors
        }]
    }
});

html:

<div>
    <canvas id="myChart"></canvas>

</div>
<div id="js-legend" class="pieLegend"></div>

回答1:


When you are adding custom legend to element of your choice, you need to also add CSS for that element. Once you add it colored boxes will be shown.

In your case you need to add below css class to div element.

.pieLegend li span{
    display: inline-block;
    width: 12px;
    height: 12px;
    margin-right: 5px;
}


来源:https://stackoverflow.com/questions/37334399/custom-legend-in-chart-js-2-1-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!