I’m trying to change the color of other slices when hovering one of them, but is a little buggy sometimes and I’m trying to understand why.
As shown in the example, there is a flickering when hovering from one slice to another and the colors don’t change right away, and also when leaving the slice the colors should reset, but it doesn’t work sometimes.
const colors = ["red", "green", "blue"];
const colorsRGBA = ["rgba(255,0,0,.25)", "rgba(0,255,0,.25)", "rgba(0,0,255,.25)"];
new Chart(document.getElementById("doughnut"), {
type: "doughnut",
data: {
labels: ["A", "B", "C"],
datasets: [
{
data: [1, 2, 3],
backgroundColor: ["red", "green", "blue"],
hoverBackgroundColor: ["red", "green", "blue"]
}
]
},
options: {
plugins: {
tooltip: {
enabled: false
},
legend: {
display: false
}
},
onHover(event, elements, chart) {
if (event.type === "mousemove") {
if (elements.length) {
chart.getDatasetMeta(0).data.forEach((data, index) => {
if (index !== elements[0].index) {
data.options.backgroundColor = colorsRGBA[index];
}
});
} else {
chart.getDatasetMeta(0).data.forEach((data, index) => {
data.options.backgroundColor = colors[index];
});
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<div style="height: 350px">
<canvas id="doughnut"></canvas>
</div>