Custom Legend in Chart.js 2.1.3

2019-07-18 00:40发布

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条回答
对你真心纯属浪费
2楼-- · 2019-07-18 01:17

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;
}
查看更多
登录 后发表回答