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

Chart.js afterDraw未触发:日期条形图添加当前日期线失败

问题排查与解决方案

你的代码里console.log没触发,大概率是两个原因:annotation插件未正确注册,或者annotation配置格式不符合插件规范,具体解决步骤如下:

1. 确认annotation插件已安装并注册

Chart.js的annotation是独立插件,默认不包含在核心库中,必须单独安装并注册:

  • 首先安装插件(如果还没装):
    npm install chartjs-plugin-annotation
    
  • 在代码中注册插件(比如组件初始化前):
    import { Chart } from 'chart.js';
    import annotationPlugin from 'chartjs-plugin-annotation';
    
    Chart.register(annotationPlugin);
    
    如果是用ng2-charts这类封装库,需要在模块中配置注册,或者在组件的chart初始化逻辑中完成注册。

2. 修正annotation配置格式

你自定义afterDraw的写法不符合annotation插件的标准配置逻辑,line类型的标注不需要手动写绘制逻辑,直接通过轴值定位即可,修改后的配置如下:

public barChartOptions: ChartOptions = {
    indexAxis: 'y',
    responsive: true,
    scales: {
      x: {
        type: 'time',
        min: new Date(
          this.todayDate.getFullYear() - 1,
          this.todayDate.getMonth() - 6,
          this.todayDate.getDate()
        ).getTime(),
        time: {
          unit: 'day',
        },
      },
      y: {
        grid: {
          display: false,
        },
      },
    },
    plugins: {
      annotation: {
        annotations: {
          todayLine: {
            type: 'line',
            // 用当前日期的时间戳设置x轴的起止点,绘制垂直线
            xMin: new Date().getTime(),
            xMax: new Date().getTime(),
            borderWidth: 3,
            borderColor: '#ff0000', // 可自定义线条颜色
            drawTime: 'afterDraw'
          },
        },
      },
    },
  };

这样配置后,插件会自动根据你设置的xMin和xMax绘制垂直参考线,无需手动编写绘制逻辑,同时能保证配置被插件正确识别执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 09:34:59