如何在图表中将"hh:mm:ss"字符串解析为时间.js 3.x



我想使用Charts.js创建一个时间线。为此,我导入了小时:分钟:秒格式的数据,如";00:00:10";。
当使用Charts.js 2.0时,可以设置解析器,从而可以将时间值作为字符串导入。

但是在升级到Charts.js 3.2.1之后,解析器选项似乎不再起作用
文档中指出,仍然可以像以前一样使用解析器。https://www.chartjs.org/docs/latest/axes/cartesian/time.html#parser

我发现了多个论坛线程解释了如何做到这一点,但它们都是在Charts.js2.x中完成的,在我的例子中已经不起作用了
使用时间字符串中的Chart.js绘制圈速
Xaxes 中的Chartjs时间

这是我的密码
由于语法分析器的脚本失败,第一个示例将不起作用。在第二个示例中,您可以看到完全相同的代码,但没有正在运行的解析器。

那么,我如何解析字符串数据,以便正确格式化并显示时间线呢?

非常感谢你的帮助。

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: "Switched",
data: [{x:"00:00:07", y: 0}, {x:"00:00:14", y: 0}, {x:"00:05:24", y: 0}],
showLine: false,
fill: false,
tooltip: "Player switched",
borderColor: "#16a085",
backgroundColor: "#16a085"
}
]},
options: {
responsive: true,
scales: {
x: {
type: 'time',
time: {
parser: 'HH:mm:ss',
unit: "seconds",
tooltipFormat: 'HH:mm:ss',
displayFormats: {
'seconds': "HH:mm:ss"
},
unitStepSize: 30
}
},
y: {
min: -1,
max: 13,
stepSize: 1,
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.1/chart.min.js"></script>
<canvas id="chart" height= "80px" style="background-color: rgb(50, 50, 50);"></canvas>

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: "Switched",
data: [{x:"00:00:07", y: 0}, {x:"00:00:14", y: 0}, {x:"00:05:24", y: 0}],
showLine: false,
fill: false,
tooltip: "Player switched",
borderColor: "#16a085",
backgroundColor: "#16a085"
}
]},
options: {
responsive: true,
scales: {
x: {},
y: {
min: -1,
max: 13,
stepSize: 1,
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.1/chart.min.js"></script>
<canvas id="chart" height= "80px" style="background-color: rgb(50, 50, 50);"></canvas>

在chart.js v3中,他们删除了moment和适配器,因此您需要将两者都添加到脚本中,它应该可以

示例:

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: "Switched",
data: [{x:"00:00:07", y: 0}, {x:"00:00:14", y: 0}, {x:"00:05:24", y: 0}],
showLine: false,
fill: false,
tooltip: "Player switched",
borderColor: "#16a085",
backgroundColor: "#16a085"
}
]},
options: {
responsive: true,
scales: {
x: {
type: 'time',
time: {
parser: 'HH:mm:ss',
unit: "seconds",
tooltipFormat: 'HH:mm:ss',
displayFormats: {
'seconds': "HH:mm:ss"
},
unitStepSize: 30
}
},
y: {
min: -1,
max: 13,
stepSize: 1,
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@0.1.1"></script>
<canvas id="chart" height= "80px" style="background-color: rgb(50, 50, 50);"></canvas>

最新更新