如何在Chart.js中固定显示最后一个数据的Tooltip?
Chart.js 固定显示最后一个数据Tooltip的解决方案
核心实现思路
通过Chart.js自定义插件,在图表绘制完成后(afterDraw钩子)手动渲染最后一个数据点的Tooltip;同时保留默认Tooltip的交互逻辑,确保鼠标悬停其他数据时正常显示对应提示。
完整代码示例
<canvas id="myChart"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> // 自定义插件:固定显示最后一个数据的Tooltip const fixedLastTooltipPlugin = { id: 'fixedLastTooltip', afterDraw: (chart) => { const { ctx, data, tooltip } = chart; const datasets = data.datasets; if (!datasets.length || datasets[0].data.length < 5) return; // 数据量不足5条时不生效 // 获取最后一个数据点的索引和对应元素 const lastIndex = datasets[0].data.length - 1; const lastPoints = datasets.map(ds => chart.getDatasetMeta(ds.index).data[lastIndex]); // 构建Tooltip所需的数据模型 const tooltipModel = { options: chart.options.plugins.tooltip, dataPoints: lastPoints.map((point, idx) => ({ datasetIndex: idx, index: lastIndex, x: point.x, y: point.y, label: data.labels[lastIndex], value: datasets[idx].data[lastIndex], datasetLabel: datasets[idx].label })) }; // 复用默认Tooltip的内容格式化逻辑 const tooltipContent = tooltip._buildTooltip(tooltipModel); if (!tooltipContent) return; // 计算Tooltip的显示位置(右侧垂直居中,可自定义) const tooltipWidth = tooltipContent.width; const tooltipHeight = tooltipContent.height; const positionX = chart.width - tooltipWidth - 10; // 右侧偏移10px const positionY = (chart.height - tooltipHeight) / 2; // 绘制Tooltip背景 ctx.save(); ctx.fillStyle = tooltip.options.backgroundColor; ctx.fillRect(positionX, positionY, tooltipWidth, tooltipHeight); // 绘制Tooltip边框 if (tooltip.options.borderWidth > 0) { ctx.strokeStyle = tooltip.options.borderColor; ctx.lineWidth = tooltip.options.borderWidth; ctx.strokeRect(positionX, positionY, tooltipWidth, tooltipHeight); } // 绘制标题文本 if (tooltipContent.title.length) { ctx.fillStyle = tooltip.options.titleColor; ctx.font = tooltip.options.titleFont.string; ctx.fillText(tooltipContent.title[0], positionX + 10, positionY + 15); } // 绘制内容文本 ctx.fillStyle = tooltip.options.bodyColor; ctx.font = tooltip.options.bodyFont.string; tooltipContent.body.forEach((line, lineIndex) => { ctx.fillText(line, positionX + 10, positionY + 30 + lineIndex * 18); }); ctx.restore(); } }; // 初始化图表 const ctx = document.getElementById('myChart').getContext('2d'); new Chart(ctx, { type: 'line', plugins: [fixedLastTooltipPlugin], data: { labels: ['周一', '周二', '周三', '周四', '周五', '周六'], datasets: [{ label: '销量', data: [12, 19, 3, 5, 2, 30], borderColor: 'rgb(75, 192, 192)', tension: 0.1 }] }, options: { plugins: { tooltip: { // 保留默认悬停Tooltip的交互 enabled: true, backgroundColor: 'rgba(0, 0, 0, 0.8)', titleColor: '#fff', bodyColor: '#fff', borderWidth: 1, borderColor: '#ddd' } } } }); </script>
关键细节说明
- 数据量校验:插件内置数据量判断,仅当数据条数≥5时才渲染固定Tooltip。
- 样式统一:直接复用默认Tooltip的配置项(背景色、字体、边框等),避免样式割裂。
- 位置可调:通过
positionX和positionY参数可自由调整固定Tooltip的显示位置,当前设置为右侧垂直居中。 - 多数据集兼容:支持同时展示多数据集最后一个数据点的信息,无需额外修改。
内容的提问来源于stack exchange,提问作者유대경
相关产品推荐
相关产品推荐

