实现流程:在Chart.js中创建一个显示在悬浮点上的垂直线,需要使用插件。这可以通过编写自定义的插件代码来完成.
编写自定义插件
import Chart from 'chart.js/auto'
// 自定义插件来绘制鼠标悬停时的垂直线
const verticalLinePlugin = {
id: 'verticalLine',
afterDraw(chart:any, args:any, options:any) {
if (chart.tooltip._active && chart.tooltip._active.length) {
// 获取激活的tooltip(即鼠标悬停处的点)
const activePoint = chart.tooltip._active[0];
const {ctx} = chart;
const {x} = activePoint.element;
const topY = chart.scales.y.top;
const bottomY = chart.scales.y.bottom;
// 保存当前的绘图状态
ctx.save();
// 绘制垂直线
ctx.beginPath();
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.lineWidth = 2;
ctx.strokeStyle = '#e5e5e5'; // 可以自定义颜色和透明度
ctx.stroke();
// 恢复之前保存的绘图状态
ctx.restore();
}
}
};
// 注册插件
Chart.register(verticalLinePlugin);
使用
// 接下来,创建图表实例时,要确保包含了tooltip的交互配置
const myChart = new Chart(ctx, {
type: 'line', // 或者你想使用的其他类型
data: {
// 数据...
},
options: {
// 图表的其他配置...
plugins: {
tooltip: {
enabled: true,
mode: 'index',
position: 'nearest',
intersect: false
}
}
}
});