You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

启用数据抽稀后Chart.js update()无法更新图表的技术问询

Chart.js 长时段数据抽稀后update()失效问题求助

我有多台温度传感器每分钟将读数上传至MySQL数据库,通过Chart.js搭建Web界面展示数据范围。因长时段(如超1个月)展示存在性能问题,启用了min-max算法的数据抽稀,并添加自定义插件修改图表背景色,静态图表运行正常。相关代码如下:

const bgPlugin = {
    id: 'customBgColor',
    beforeDraw: (chart, args, options) => {
        const {ctx} = chart;
        ctx.save();
        ctx.globalCompositeOperation = 'destination-over';
        ctx.fillStyle = options.color || "#f5f3ef";
        ctx.fillRect(0, 0, chart.width, chart.height);
        ctx.restore();
    }
};

var config = {
  type: 'line',
  data: data,
  options: {
    parsing: false,
    animation: false,
    plugins: {
      decimation: {
        enabled: true,
        algorithm: 'min-max',
      },
      customBgColor: {
          color: "#f5f3ef",
      }
    },
    scales: {
        x: {
            type: 'time',
            time : {
                unit: 'day',
            },
            adapters: {
                date: {
                    zone: "America/Los_Angeles",
                },
            },
        },
    },
  },
  plugins: [bgPlugin],
};

近期新增定时从MySQL获取最新读数并更新图表的功能,相关代码如下:

function getFreshTemps() {
    var tempSensors = '';
    var starting = '?unit='+theUnit;
    var readyToUpdate = false;
    
    if(!Object.is(latestOne, null)) {
        starting += '&sk=' + latestOne;
    }
    
    const theURL = 'REDACTED' + starting;
    fetch(theURL)
    .then((response) => {
        if(!response.ok) {
            throw new Error('HTTP error, status = '+response.status);
        }
        return response.json();
    })
    .then((isParsed) => {
        if(isParsed.lastKey > latestOne) {
            latestOne = isParsed.lastKey;
        }
        if(isParsed.rows !== undefined) {
            isParsed.rows.forEach((theRow) => {
                if(sensorIndices[theRow['sensor']] !== undefined) {
                    thaChart.data.datasets[sensorIndices[theRow['sensor']]].data.push({x: theRow['chartTime'], y: theRow['temp']});
                    readyToUpdate = true;
                }
            });
            if(readyToUpdate) {
                thaChart.update();
                readyToUpdate = false;
            }
        }
    });
}

同时通过以下代码设置定时更新:

window.onload = setInterval(getFreshTemps, 15000);

其中latestOne为PHP生成的全局变量,代表MySQL表中最新ID;sensorIndices为PHP生成的数组,映射传感器名称与数据集索引。

短时段(数小时至1天)图表可正常更新,但长时段(如默认展示3天,已触发数据抽稀)时update()失效。此外发现触发问题的数据点数量与屏幕宽度相关:缩小窗口后执行getFreshTemps()更新的点,在窗口最大化后无法显示,后续更新的点会显示但存在数据间隙。

我使用Chart.js 3.9.1,未找到更新时强制重新执行数据抽稀的方法,特此咨询解决办法。


内容的提问来源于stack exchange,提问作者WinnPh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 21:13:20