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: function(chart) {
const labels = document.createElement("ul");
labels.style.display = 'flex';
labels.style.justifyContent = 'center';

chart.data.datasets.forEach((dataset, i) => {
const item = document.createElement("li");
item.style.listStyle = 'none';
item.style.display = 'inline';

const icon = document.createElement("div");
icon.style.width = icon.style.height = '15px';
icon.style.display = 'inline-block';
icon.style.margin = '0 6px';
icon.style.backgroundColor = dataset.borderColor;

item.appendChild(icon); // add colored square
item.innerHTML += dataset.label; // add label text
labels.appendChild(item);
});
return labels.outerHTML;
},
legend: { display: false, position: 'bottom' }
}
});

const legend = document.getElementById('chart-legends');
legend.innerHTML = myChart.generateLegend(); // generates HTML

The new legend doesn’t replace the default label. Unless you wish to display both legends, you should hide the default legend using display: false.

No behaviors are included in these HTML legends. You need to implement them yourself using JavaScript events. The following screenshot shows the result of the previous code:

Legends created with HTML. Code: Legend/legend-1-gen-labels.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset