1

我很难让 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。

4

1 回答 1

1

您的配置错误,在 v3 中您必须定义比例的方式已更改,请阅读迁移指南:https ://www.chartjs.org/docs/master/getting-started/v3-migration.html#scales

工作示例:

<html>

<head>
  <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: {
            x: {
              type: 'time',
            }
          }
        }
      });

    };
  </script>
</body>
</html>

于 2021-06-29T16:41:53.140 回答