I am using ChartJS v2.9.3.
I am trying to add to the time line chart a conditional vertical background color that is displayed depending on if dataset's y-value is above a threshold.
The thread Background colour of line charts in chart.js gave me the idea to use the following plugin
const backgroundPlugin = {
beforeDatasetDraw(chart, easing) {
const ctx = chart.chart.ctx;
const chartArea = chart.chartArea;
ctx.save();
const colors = [
'red',
'green',
'yellow',
'blue'
];
const randomNumber = Math.floor(Math.random() * colors.length);
// Set random background color to show how many times this function is called
ctx.fillStyle = colors[randomNumber];
console.log('refreshing background');
chart.getDatasetMeta(0).data.forEach((data, index, all) => {
// Check if value > threshold (here 350)
if (
chart.config.data.datasets[0].data[index].y > 350
) {
const nextPointX =
index === all.length - 1 ?
chartArea.left :
all[index + 1]._model.x;
// Create vertical rectangle of color between current point and next point
ctx.fillRect(
nextPointX,
chartArea.top,
Math.abs(all[index]._model.x - nextPointX),
chartArea.bottom - chartArea.top
);
}
});
ctx.restore();
}
};
The problem I observed is that every time I hover on one point of the line chart, the plugin's beforeDatasetDraw
function gets called a huge number of time.
The problem can be seen on this JSFiddle : https://jsfiddle.net/avocado1/hgpukame/88/#
This is a problem for me because in my real case that causes a performance issue (I work with a more than 20.000 points datasets and I would like to have 5 different background colors depending on 5 different thresholds, meaning there could be 5 comparisons for each point of my dataset).
Would anyone have any clue on how to prevent hovering events to cause calls to my plugin ? (Or have any workaround to create a conditional background once and for all ?)