2

我有点卡在 Chartjs 上。我想将日期作为 x 轴标签,但无论我尝试什么,我都会收到错误消息。这是我的代码:

<html>

<head>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css">
    <meta charset="utf-8" />
</head>

<body>

    <div style="width:75%;">
        <canvas id="canvas"></canvas>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
    <script>
        var date0 = new Date((new Date()).getTime() - 50000);
        var date1 = new Date();
        var date2 = new Date((new Date()).getTime() + 50000);

        var chartData = {
            type: 'line',
            data: {
                datasets: [{
                    label: 'A label',
                    backgroundColor: 'rgb(255,0,0)',
                    borderColor: 'rgb(255,0,0)',
                    data: [
                        { x: date0, y: 10 },
                        { x: date1, y: 11 },
                        { x: date2, y: 15 }
                    ],
                    fill: false,
                    yAxisID: 'y-axis-1',
                }]
            },
            options: {
                responsive: true,
                scales: {
                    xAxes: [{
                        type: 'time',
                        time: {
                            unit: 'second'
                        }
                    }],
                    yAxes: [{
                        type: 'linear',
                        display: true,
                        position: 'left',
                        id: 'y-axis-1',
                    }]
                }
            }
        }

        window.onload = function () {
            var ctx = document.getElementById('canvas').getContext('2d');
            window.myLine = new Chart(ctx, chartData);
        };

    </script>
</body>

</html>

我总是收到以下错误:

未捕获的错误:此方法未实现:找不到适配器或提供了不完整的集成。

这暗示了chartData对象的格式不正确,但是由于我非常接近 Chartjs 的文档,所以我不知道在哪里。任何人都可以发现错误吗?

在此先感谢您的帮助。

4

1 回答 1

2

您应该包含 Chart.js 包,其中包含 Moment.js 库(格式化日期和时间所需),如下所示:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>

在此处查看文档:https ://www.chartjs.org/docs/latest/getting-started/installation.html#bundled-build

于 2020-07-19T17:36:46.507 回答