首页 > 解决方案 > 每次我悬停一个点时,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 次比较我的数据集的点)。

有人对如何防止悬停事件导致对我的插件的调用有任何线索吗?(或者有任何解决方法可以一劳永逸地创建条件背景?)

标签: performancechart.js

解决方案


推荐阅读