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

如何在ChartJS Annotations上实现鼠标悬停显示自定义标签功能

ChartJS Annotations 悬停显示自定义标签实现方案

完全可以实现和原生数据点悬停逻辑一致的自定义标签效果,核心通过chartjs-plugin-annotation自带的事件回调复用ChartJS原生tooltip能力即可:

核心实现步骤

  • 给目标annotation元素配置enter(鼠标进入注解)、leave(鼠标离开注解)事件回调
  • 进入注解时,构造和原生数据点悬停参数结构一致的active元素,调用tooltip.setActiveElements()手动触发原生tooltip渲染
  • 离开注解时,清空active元素隐藏tooltip,和原生交互逻辑完全对齐

完整代码示例

// 需提前注册chartjs-plugin-annotation插件
const myChart = new Chart(document.getElementById('myChart'), {
  type: 'line',
  data: {
    labels: ['1月', '2月', '3月', '4月', '5月'],
    datasets: [{
      label: '月度销量',
      data: [12, 19, 7, 15, 9],
      borderColor: '#4bc0c0'
    }]
  },
  options: {
    plugins: {
      annotation: {
        annotations: {
          warnLine: {
            type: 'line',
            yMin: 10,
            yMax: 10,
            borderColor: '#ff6384',
            borderWidth: 2,
            // 自定义注解的tooltip内容
            customTip: '库存预警阈值:≥10件',
            // 鼠标进入注解触发
            enter: (ctx) => {
              const chartInstance = ctx.chart;
              // 构造符合原生tooltip要求的激活元素
              const activeItem = [{
                datasetIndex: 0,
                index: 0,
                // 注入自定义内容
                annotationTip: ctx.element.options.customTip
              }];
              // 触发原生tooltip展示
              chartInstance.tooltip.setActiveElements(activeItem, ctx.event);
              chartInstance.update();
            },
            // 鼠标离开注解触发
            leave: (ctx) => {
              ctx.chart.tooltip.setActiveElements([], null);
              ctx.chart.update();
            }
          }
        }
      },
      tooltip: {
        callbacks: {
          label: (context) => {
            // 区分是注解触发还是原生数据点触发
            if (context.annotationTip) {
              return context.annotationTip;
            }
            // 原生数据点走原有展示逻辑
            return `${context.dataset.label}:${context.raw}件`;
          }
        }
      }
    }
  }
});

注意事项

  • 如果使用v2及以上版本的chartjs-plugin-annotation,需要先给注解配置events: ['mousemove', 'mouseout']开启事件监听,再配置enter和leave回调
  • 所有tooltip的样式、延迟展示、消失逻辑都和原生完全复用,不需要额外自定义悬浮层样式
  • 支持给不同类型的注解(线、矩形、点、文本)分别配置不同的自定义tooltip内容,互相独立不干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:45:10