如何实现Chart.js实时图表放大后显示隐藏的时间标签
问题概述
我正在使用HTML、CSS和JS开发实时折线图表,当前仅每30秒显示一个时间标签。希望在放大图表时,原本隐藏的非30秒间隔的时间标签能够自动显示,但目前该功能未实现。
相关代码
JavaScript代码
function formatTime(seconds) { if (seconds < 60) { if (seconds % 30 === 0) { return '0:' + ('0' + seconds).slice(-2); // 格式化为 "0:SS" } else { return ''; } } else { const minutes = Math.floor(seconds / 60); const remainingSeconds = seconds % 60; if (remainingSeconds % 30 === 0 || remainingSeconds == 0) { return minutes + ':' + ('0' + remainingSeconds).slice(-2); // 格式化为 "M:SS" } else { return ''; } } } const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: [], // 时间标签或分类 datasets: [{ label: '进气温度', data: [], // 第一个数据集的数据点 backgroundColor: 'rgba(0, 123, 255, 0.5)', borderColor: 'rgba(0, 123, 255, 1)', borderWidth: 1, fill: false, pointRadius: 0 }, { label: '储罐温度', data: [], // 第二个数据集的数据点 backgroundColor: 'rgba(255, 99, 132, 0.5)', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 1, fill: false, pointRadius: 0 }, { label: '初始峰值', data: [], // 第三个数据集的数据点 backgroundColor: 'rgba(0, 255, 0, 0.5)', borderColor: 'green', fill: true, pointRadius: 0 }] }, options: { scales: { y: [{ beginAtZero: true, title: { display: true, text: '温度' }, ticks: { beginAtZero: true } }], x: [{ type: 'time', time: { parser: 'mm:ss', unit: 'second', stepSize: 30, displayFormats: { second: 'm:ss' }, tooltipFormat: 'm:ss' }, title: { display: true, text: '时间 (MM:SS)' }, ticks: { autoSkip: true, maxTicksLimit: 20, callback: function (value, index, values) { const totalSeconds = moment.duration(value).asSeconds(); return formatTime(totalSeconds); } } }] }, plugins: { zoom: { pan: { enabled: true, mode: 'x' }, zoom: { wheel: { enabled: true }, pinch: { enabled: true }, mode: 'x' } } } } });
HTML代码
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2"></script> <canvas id="myChart"></canvas>
图表示例

内容的提问来源于stack exchange,提问作者Sinan Urgun
相关产品推荐
相关产品推荐

