performance - 每次我悬停一个点时,ChartJS 折线图都会调用插件
问题描述
我正在使用 ChartJS v2.9.3。
我正在尝试向时间线图添加一个有条件的垂直背景颜色,该颜色取决于数据集的 y 值是否高于阈值。
chart.js 中折线图的线程背景颜色给了我使用以下插件的想法
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();
}
};
我观察到的问题是,每次我将鼠标悬停在折线图的一个点上时,插件的beforeDatasetDraw
函数都会被调用很多次。
这个问题可以在这个 JSFiddle 上看到:https ://jsfiddle.net/avocado1/hgpukame/88/#
这对我来说是个问题,因为在我的实际情况下会导致性能问题(我使用超过 20.000 个点的数据集,我希望根据 5 个不同的阈值有 5 种不同的背景颜色,这意味着每个可能有 5 次比较我的数据集的点)。
有人对如何防止悬停事件导致对我的插件的调用有任何线索吗?(或者有任何解决方法可以一劳永逸地创建条件背景?)
解决方案
推荐阅读
- cucumber - Cucumber V4 [io.cucumber] 未识别 @Given/When/Then 并给出错误“无法解析导入 cucumber.api.java.en.When”
- javascript - 如何让我的 Javascript 函数在部分 html 页面上工作?
- gitlab - 我是否需要安装 Docker 才能在 Windows 中安装 gitlab-runner?
- python - 我必须在周期中改变什么?
- swift - alertview textField 返回空字符串
- qt - 不是顶级小部件时如何接收dropEvent?
- image - 来自 picsum 的 533 响应后 Flutter NetworkImage 抛出错误
- java - 从深层链接中的意图获取空值
- sql - 甲骨文资料库
- odata - 在 SAPUI5 列表中绑定 OData 属性