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

如何在Chart.js中实现悬停两点间线段区域时显示tooltip

实现Chart.js悬停线段时显示Tooltip

嘿,这个需求我之前做项目的时候刚好遇到过!Chart.js默认确实只在鼠标精准悬停数据点时才弹出tooltip,但要让线段区域也能触发其实有两种常用方案,看你需要的精度来选:

方案一:简单快速——扩大线段的交互触发范围

如果只是想让鼠标靠近线段时就触发tooltip,不用显示线段上的插值数值,直接配置elements.line.interactionRadius就行,这个属性可以设置线段的“可交互半径”,数值越大,鼠标离线段越远也能触发:

const myLineChart = new Chart(document.getElementById('myChart'), {
  type: 'line',
  data: {
    labels: ['1月', '2月', '3月', '4月'],
    datasets: [{
      label: '月度数据',
      data: [12, 19, 3, 5],
      borderColor: '#FF6384',
      tension: 0.1
    }]
  },
  options: {
    elements: {
      line: {
        // 调整这个值,比如10,鼠标离线段10px内就会触发
        interactionRadius: 10
      }
    },
    interaction: {
      // 设为nearest,优先找最近的交互元素
      mode: 'nearest',
      intersect: true
    },
    plugins: {
      tooltip: {
        // 可选:让tooltip跟随鼠标位置
        position: 'cursor'
      }
    }
  }
});

方案二:精准显示线段插值——自定义Tooltip内容

如果需要在悬停线段时,显示当前鼠标位置对应的插值(不是数据点的数值,而是线段上的中间值),就需要配合Tooltip的回调函数来计算:

const myLineChart = new Chart(document.getElementById('myChart'), {
  type: 'line',
  data: {
    labels: ['1月', '2月', '3月', '4月'],
    datasets: [{
      label: '月度数据',
      data: [12, 19, 3, 5],
      borderColor: '#FF6384',
      tension: 0.1
    }]
  },
  options: {
    elements: {
      line: {
        interactionRadius: 15 // 先扩大交互范围,确保容易触发
      }
    },
    interaction: {
      mode: 'index',
      intersect: false // 不要求精准命中,只要靠近线段就触发
    },
    plugins: {
      tooltip: {
        position: 'cursor',
        callbacks: {
          // 自定义tooltip标签,计算线段插值
          label: function(context) {
            const chart = context.chart;
            const xScale = chart.scales.x;
            const yScale = chart.scales.y;
            const mouseX = chart._lastMousePosition.x;
            const currentIndex = context.dataIndex;
            const nextIndex = (currentIndex + 1) < context.dataset.data.length ? currentIndex + 1 : currentIndex;
            
            // 获取当前和下一个数据点的数值与x轴刻度
            const currentY = context.dataset.data[currentIndex];
            const nextY = context.dataset.data[nextIndex];
            const currentX = xScale.ticks[currentIndex].value;
            const nextX = xScale.ticks[nextIndex].value;
            
            // 计算鼠标位置对应的x轴数值
            const mouseXValue = xScale.getValueForPixel(mouseX);
            
            // 线性插值计算线段上的y值
            const interpolatedY = currentY + (nextY - currentY) * (mouseXValue - currentX) / (nextX - currentX);
            
            return `当前数值: ${interpolatedY.toFixed(2)}`;
          }
        }
      }
    }
  }
});

注意:如果你的x轴是时间轴或者连续数值轴,上面的插值计算逻辑完全适用;如果是分类轴,可能需要调整x值的计算方式,但核心思路是一致的。

内容的提问来源于stack exchange,提问作者TRO JEAN.CEDRIC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:07:47