Last active
September 8, 2021 08:29
-
-
Save waaronking/7a3ea397c3b529176d740ec83c2847d0 to your computer and use it in GitHub Desktop.
ChartJS 3.5.1 Custom Legend Plugin Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* This script requires the following elements in order to run: | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script> | |
<div id="legend-id"></div> | |
<canvas id="chart-id"></canvas> | |
*/ | |
var data = { | |
labels: [ | |
'Red', | |
'Blue', | |
'Yellow' | |
], | |
datasets: [{ | |
label: 'My First Dataset', | |
data: [300, 50, 100], | |
backgroundColor: [ | |
'rgb(255, 99, 132)', | |
'rgb(54, 162, 235)', | |
'rgb(255, 205, 86)' | |
], | |
hoverOffset: 4 | |
}] | |
}; | |
var options = { | |
plugins: { | |
tooltip: { | |
enabled: false | |
}, | |
legend: { | |
display: false | |
} | |
} | |
}; | |
const context = document.querySelector("#chart-id"); | |
const chart = new Chart(context, { | |
type: "doughnut", | |
data, | |
options, | |
plugins: [{ | |
beforeInit: function(chart, args, options) { | |
// Make sure we're applying the legend to the right chart | |
if (chart.canvas.id === "chart-id") { | |
const ul = document.createElement('ul'); | |
chart.data.labels.forEach((label, i) => { | |
ul.innerHTML += ` | |
<li> | |
<span style="background-color: ${ chart.data.datasets[0].backgroundColor[i] }"> | |
${ label } : ${ chart.data.datasets[0].data[i] } | |
</span> | |
</li> | |
`; | |
}); | |
return document.getElementById("legend-id").appendChild(ul); | |
} | |
return; | |
} | |
}] | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment