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
相关产品推荐
相关产品推荐

