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

如何在Chart JS渐进式折线图中用JavaScript获取当前点的值

在Chart.js渐进式折线图中获取动画过程的当前值

1. 可以用setInterval实现,但需结合Chart.js动画状态

这种方式可行,但需要依赖Chart.js内部的动画状态属性,同时要注意在动画结束后清理定时器避免内存泄漏。示例代码如下:

// 初始化折线图
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['第1秒', '第2秒', '第3秒', '第4秒', '第5秒'],
    datasets: [{
      label: '渐进数据',
      data: [10, 20, 15, 25, 30],
      borderColor: '#2196F3',
      fill: false,
      animation: {
        duration: 20000, // 总动画时长20秒
        easing: 'linear' // 线性动画便于进度计算
      }
    }]
  }
});

let intervalId;
// 动画开始时启动定时器
myChart.options.animation.onStart = function() {
  intervalId = setInterval(() => {
    // 获取当前动画进度(0~1)
    const progress = myChart.animation.currentStep / myChart.animation.numSteps;
    // 计算每个数据点的当前插值
    const currentValues = myChart.data.datasets[0].data.map(val => val * progress);
    console.log('当前折线各点值:', currentValues);
  }, 1000);
};

// 动画结束时清除定时器
myChart.options.animation.onComplete = function() {
  clearInterval(intervalId);
};

注意:不同Chart.js版本的内部属性可能有差异,若currentStep或numSteps无法获取,可尝试通过animationObject.current / animationObject.total获取进度。

2. 更简便的方法:使用Chart.js内置onProgress钩子

这是官方推荐的方式,无需手动维护定时器,能精准监听动画进度,代码更简洁且贴合框架设计:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['第1秒', '第2秒', '第3秒', '第4秒', '第5秒'],
    datasets: [{
      label: '渐进数据',
      data: [10, 20, 15, 25, 30],
      borderColor: '#2196F3',
      fill: false,
      animation: {
        duration: 20000,
        easing: 'linear',
        // 动画进度回调钩子
        onProgress: function(anim) {
          // 严格每秒打印一次(通过已流逝时间判断)
          const elapsed = Math.floor(anim.currentStep / anim.numSteps * 20000);
          if (elapsed % 1000 === 0) {
            const progress = anim.animationObject.current / anim.animationObject.total;
            const currentValues = myChart.data.datasets[0].data.map(val => val * progress);
            console.log('当前折线各点值:', currentValues);
          }
        }
      }
    }]
  }
});

如果不需要严格每秒一次,直接在onProgress内打印即可获取每一帧的实时值;若只关心单个点的当前值,取currentValues对应索引的结果即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:40:00