2👍
✅
I don’t understand your first point, but to address your second point:
The below snippet sets a default colour for each bar (‘lightgrey’). When a bar is clicked all bars are set to their original colour and the clicked bar is set to ‘red’. The benefit of this approach is that the starting colour of each bar can be different and will correctly toggle to ‘red’ and back.
let background = ['lightgrey', 'lightgrey', 'lightgrey', 'lightgrey'],
myChart = new Chart(document.getElementById('chart'), {
type: 'bar',
data: {
labels: ['a', 'b', 'c', 'd'],
datasets: [{
label: 'series1',
data: [7, 10, 8, 2],
backgroundColor: background.slice() // using .slice here 'clones' the array.
}]
},
options: {
maintainAspectRatio: false,
onClick: function(e, elems) {
if (elems.length) {
elems[0]._chart.config.data.datasets[0].data.forEach((value, index) => {
// set element to the original colour (resets all).
elems[0]._chart.config.data.datasets[0].backgroundColor[index] = background[index];
if (index == elems[0]._index) {
// set the clicked element to red.
elems[0]._chart.config.data.datasets[0].backgroundColor[index] = 'red';
}
});
myChart.update(); // if you don't want the animation use 'myChart.update(0);' instead.
}
}
}
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>
Notes:
- the legend uses the colours of the first point so when it’s clicked the legend colour changes also.
- this only works on the first dataset (
elems[0]...datasets[0]
).
Source:stackexchange.com