HTML legends
If you have a very complex legend or wish to display a legend outside the Canvas mixed with the HTML in your page, you can generate custom HTML legends. To create them, you need an empty <div>
block:
<div id="chart-legends"></div>
So, the legend can be attached to the page’s body. Then, you implement a callback
function for the Chart.defaults.global.legendCallback
property or options.legendCallback
that returns the HTML for the legend. You can create the content dynamically and apply CSS styles with property values copied from the chart. The HTML is generated with chart.generateLegend()
.
It’s easier with an example. The following code implements a simple HTML legend from an HTML list. You can run the full code in Legend/legend-2-html-callback.html
:
const myChart = new Chart("myChart", { type: 'line', data: { labels: ['Day 1','Day 2','Day 3','Day 4','Day 5','Day 6'], datasets: datasets, }, options: { legendCallback...