我很难让 chart.js 在时间轴上运行。
我有以下简化代码:
<html>
<head>
<!--
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
-->
<script src="https://cdn.jsdelivr.net/npm/moment"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
</head>
<body>
<canvas id="chart" width="800" height="400"></canvas>
<script type="text/javascript">
window.onload = function () {
var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx,{
type: 'line',
data: {
datasets:[ {
data: [
{ x: '2017-01-06', y: 50 },
{ x: '2017-01-15', y: 45 },
{ x: '2017-03-07', y: 35 },
]
} ]
},
options: {
scales: {
xAxes: [ { type: 'time', } ]
}
}
});
};
</script>
</body>
</html>
包含最新的 3.4.0 chart.js 时,时间轴的格式不正确(数据点均匀分布在 x 轴上)。但是在使用 2.9.3 版本时,它显示正确(数据点分布不均匀)。
小提琴不工作(使用 3.4.0):https
:
//jsfiddle.net/ungoq8j6/1/ 小提琴工作(使用 2.9.3):https ://jsfiddle.net/ungoq8j6/2/
根据文档(对该主题完全模糊),您必须包含一个日期库和一个适配器(此处为 moment.js + chartjs-adapter-moment)。
该脚本仅在客户端使用,因此没有可用的 node.js/npm。