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

如何在Chart.js中获取时间值对应的像素以绘制线条?

解决Chart.js时间轴getPixelForValue返回NaN的问题

问题核心

使用Chart.js横向条形图(indexAxis: 'y')时,X轴为时间类型,调用getPixelForValue传入日期字符串返回NaN,无法获取正确像素值绘制线条。

修复要点

  1. 传入Date对象而非字符串
    当X轴设置parsing: false时,Chart.js不会自动解析日期字符串,必须手动将日期转为Date对象,时间轴才能识别该值并计算对应像素。

  2. 修正插件回调的实例引用
    插件的beforeDraw回调第一个参数是当前图表实例,应直接使用该实例而非全局myChart,避免实例未初始化或不匹配的问题;同时注意参数拼写错误(char应为chart)。

  3. 统一时间格式为Date对象
    不仅是getPixelForValue的参数,图表配置中的min、数据中的x值都建议转为Date对象,确保时间轴解析一致。

修改后的代码

const connectorLines = {
    id: 'connectorLines',
    beforeDraw(chart, args, options){
        const { ctx, scales: { x, y } } = chart;
            
        // 将日期字符串转为Date对象后传入
        const targetDate = new Date('2021-11-07T00:23:35');
        const xPixel = x.getPixelForValue(targetDate);
        console.log(xPixel); // 现在会返回正确的像素值
        
        drawArrow(ctx, xPixel, y.getPixelForValue('C'), xPixel, y.getPixelForValue('A1') - 4.5, 1, 'rgba(74, 122, 181)');
    }
};

const config = {
    type: 'bar',
    options: {  
         scales: { 
             x: {
                parsing: false,
                position: 'top',
                type: 'time',
                min: new Date('2021-11-07T00:23:20'), // 转为Date对象
                bounds: 'data',
                time: {
                    unit: 'minute'
                }
             } 
         }, 
        indexAxis: 'y',
        grouped: false,
        elements: {
          bar: {
            borderWidth: 2,
          }
        },
        responsive: true,
        plugins: {
          legend: {
            position: 'right',
          }
        }
      },
        data: {
          datasets: [{
            label: 'S_1',
            data: 
                [
                    {y:'C', x:[new Date('2021-11-07T00:23:35'), new Date('2021-11-07T00:23:35')], id: 'id1' },
                    {y:'A', x:[new Date('2021-11-07T00:23:41'), new Date('2021-11-07T00:24:20')], id: 'id2'}, 
                    {y:'A1', x:[new Date('2021-11-07T00:23:35'), new Date('2021-11-07T00:23:41')], id: 'id3'}
                ],
                backgroundColor: [
                  'rgba(74, 122, 181)'
                ],
                borderColor: [
                  'rgba(193, 193, 193)'
                ],
                borderWidth: 1,
                borderSkipped: true
          }]
        },
        plugins: [ connectorLines ],
};

额外提示

  • 如果不想手动转换所有日期字符串,可以将X轴的parsing: false改为parsing: true,Chart.js会自动解析标准ISO格式的日期字符串。
  • 确保已正确引入Chart.js的时间轴适配器(如chartjs-adapter-date-fns),没有适配器的话时间轴无法正常工作,也会导致getPixelForValue返回NaN。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:37:25