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

Chart.js折线图鼠标悬停同时绘制水平与垂直指示线问题求助

解决方案

你只需要在原有绘制垂直线的逻辑基础上,补充获取当前数据点的Y轴坐标、绘制水平线的逻辑即可,修改后的代码如下:

首先是修改后的lineOnHover函数:

window.lineOnHover = function(){        
    Chart.defaults.LineWithLine = Chart.defaults.line;
    Chart.controllers.LineWithLine = Chart.controllers.line.extend({
    draw: function(ease) {
      Chart.controllers.line.prototype.draw.call(this, ease);

      if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
         var activePoint = this.chart.tooltip._active[0],
             ctx = this.chart.ctx,
             x = activePoint.tooltipPosition().x,
             y = activePoint.tooltipPosition().y, // 新增:获取当前悬浮点的Y坐标
             topY = this.chart.legend.bottom,
             bottomY = this.chart.chartArea.bottom,
             leftX = this.chart.chartArea.left, // 新增:获取图表区域左边界
             rightX = this.chart.chartArea.right; // 新增:获取图表区域右边界

         // 保存画布状态,两种线共用一套样式即可
         ctx.save();
         ctx.lineWidth = 1;
         ctx.setLineDash([3,3]);
         ctx.strokeStyle = '#FF4949';
         
         // 绘制垂直线
         ctx.beginPath();
         ctx.moveTo(x, topY);
         ctx.lineTo(x, bottomY);
         ctx.stroke();
         
         // 新增:绘制水平线
         ctx.beginPath();
         ctx.moveTo(leftX, y);
         ctx.lineTo(rightX, y);
         ctx.stroke();
         
         ctx.restore();
      }
    }
    });
}

改动说明

  • 新增获取悬浮点的Y轴坐标、图表区域左右边界的参数
  • 把公共的样式设置提到前面,避免重复赋值
  • 补充了水平线的绘制逻辑,样式和原有垂直线完全一致
  • 原有图表初始化的代码不需要做任何修改,直接使用即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:45:03