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

ChartJS3.6版本实现鼠标悬停时绘制垂直竖线的问题咨询

ChartJS 3.6 悬停垂直竖线实现方案

原v2版本自定义控制器方案失效原因

ChartJS 3.x 重构了控制器继承逻辑、内部渲染生命周期及Tooltip相关API结构,v2版本通过继承LineController重写draw方法的实现方式不再兼容3.x版本。

标准实现方案

ChartJS 3.x 官方推荐使用插件生命周期钩子实现自定义渲染逻辑,已验证可用的afterDraw钩子方案为符合规范的正确实现,优化后的通用版本如下:

plugins: [{
  id: 'verticalHoverLine', // 插件唯一标识
  afterDraw: (chart) => {
    // 仅在Tooltip激活时渲染竖线
    if (!chart.tooltip?._active?.length) return;

    const activePoint = chart.tooltip._active[0];
    const lineX = activePoint.element.x;
    // 自动适配y轴,支持多y轴场景下取第一个左右侧y轴的边界
    const yAxis = Object.values(chart.scales).find(scale => ['left', 'right'].includes(scale.position));
    if (!yAxis) return;

    const ctx = chart.ctx;
    ctx.save();
    // 按需调整虚线间隔,不需要虚线可删除该行
    ctx.setLineDash([2, 2]);
    ctx.beginPath();
    ctx.moveTo(lineX, yAxis.top);
    ctx.lineTo(lineX, yAxis.bottom);
    ctx.lineWidth = 1;
    // 按需调整线条颜色透明度
    ctx.strokeStyle = 'rgba(66, 66, 66, 0.6)';
    ctx.stroke();
    ctx.restore();
  }
}]

全局生效配置

如果需要所有图表默认都带该悬停竖线,可注册为全局插件:

import { Chart } from 'chart.js';

Chart.register({
  id: 'verticalHoverLine',
  afterDraw: /* 上述相同逻辑 */
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:54:05