You need to enable JavaScript to run this app. 如何自定义Chart.js折线图的工具提示以匹配预期展示效果
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义Chart.js折线图的工具提示以匹配预期展示效果

Chart.js 折线图工具提示自定义配置

当前实现状态

var chart = new Chart(ctx, {
  type: "line",
  data: {
    labels: This.xAxis,
    datasets: [{
      backgroundColor: gradient,
      pointBackgroundColor: "white",
      borderWidth: 1,
      borderColor: "#5946B0",
      pointRadius: 2,
      displayColors: false,
      data: This.yAxis
    }]
  },
  options: {
    title: {
      display: false,
      text: "Test"
    },
    tooltips: {
      backgroundColor: "#FAFAFA",
      borderColor: "lightgreen",
      borderWidth: 1,
      titleFontColor: "black",
      titleFontStyle: "normal",
      displayColors: false,
      bodyFontColor: "black"
    },
    legend: {
      display: false
    },
    plugins: {
      zoom: {
        pan: {
          enabled: true,
          mode: "x",
          speed: 10,
          threshold: 10
        },
        zoom: {
          enabled: true,
          mode: "y"
        }
      }
    }
  }
});

工具提示调整配置要点

在现有tooltips配置块补充对应参数,即可匹配目标展示效果:

  • 交互模式配置:设置mode: 'index'、intersect: false,鼠标在对应x坐标区域内即可触发提示,无需精准落在折线点上,覆盖同x位置的所有数据点
  • 样式细节调整:
    • 配置cornerRadius: 8实现提示框圆角
    • 配置padding: 12增加提示框内边距,避免内容贴边
    • 配置caretSize: 6调整提示框指向数据点的三角标识尺寸
  • 展示内容自定义:通过callbacks钩子控制提示框内的文案格式,示例配置如下:
callbacks: {
  // 自定义提示框标题为当前x轴标签
  title: (items) => items[0].label,
  // 自定义提示框内容为对应y轴数值
  label: (item) => `统计值:${item.parsed.y}`
}

内容的提问来源于stack exchange,提问作者mohammad reza esmailzadeh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.11 23:15:03