Chart.js如何根据X轴时间值获取对应Y轴高度并在平滑曲线上标记红点
解决方案
你遇到的点不贴合平滑曲线的问题,核心原因是tension: 0.5开启了贝塞尔曲线平滑效果,原始数据点之间的连线不是直线,直接用线性插值计算或者硬加原始数据点,肯定无法和生成的平滑曲线对齐。下面给出两种可直接落地的实现方案:
方案1:使用chartjs-plugin-annotation插件(推荐,无需手动计算坐标)
这是最省心的方案,插件会自动根据你配置的曲线参数计算对应时间点的准确坐标,完全贴合平滑曲线:
- 先安装并注册插件:
npm install chartjs-plugin-annotation
import annotationPlugin from 'chartjs-plugin-annotation'; Chart.register(annotationPlugin);
- 在原有图表配置的
options.plugins节点下新增annotation配置,替换为你需要的当前时间即可:
plugins: { // 保留原有tooltip、legend的配置不变 annotation: { annotations: { // 可选配置:添加当前时间对应的垂直参考线 timeLine: { type: 'line', xMin: new Date('2021-11-04T14:00:00'), // 替换为你的当前时间 xMax: new Date('2021-11-04T14:00:00'), borderColor: 'red', borderWidth: 1, borderDash: [5, 5] }, // 曲线上的红点标记 currentTidePoint: { type: 'point', xValue: new Date('2021-11-04T14:00:00'), // 替换为你的当前时间 yValue: 'auto', backgroundColor: 'red', radius: 5, borderWidth: 2, borderColor: '#fff' } } } }
方案2:手动计算插值(无需引入额外插件)
如果你不想引入第三方插件,可以调用Chart.js内置的插值方法计算出目标时间点在平滑曲线上的准确y值,再添加到标记数据集即可:
// 替换为你的当前时间 const targetTime = new Date('2021-11-04T14:00:00').getTime(); // 定位目标时间落在原始数据的哪两个相邻点之间 let pointIndex = 0; for (; pointIndex < labels.length - 1; pointIndex++) { const t1 = new Date(labels[pointIndex]).getTime(); const t2 = new Date(labels[pointIndex + 1]).getTime(); if (targetTime >= t1 && targetTime <= t2) break; } // 计算目标时间点在平滑曲线上的像素坐标,再转换为y轴数值 const targetXPixel = chart.scales.xAxis.getPixelForValue(targetTime); const interpolatedYPixel = chart.data.datasets[0]._meta[0].data[pointIndex].interpolate({x: targetXPixel}).y; const targetYValue = chart.scales.yAxis.getValueForPixel(interpolatedYPixel); // 最后将{x: targetTime, y: targetYValue}添加到你的标记数据集,更新图表即可
内容的提问来源于stack exchange,提问作者finlamit
相关产品推荐
相关产品推荐

