【问题标题】:Chart.js chart not being displayedChart.js 图表未显示
【发布时间】:2021-01-03 18:57:10
【问题描述】:

我正在尝试使用和测试一个简单的 chart.js 图表,但无论我做什么,我似乎都无法显示图表。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <title>My Chart.js Chart</title>
</head>
<body>
  <div class="container">
    <canvas id="myChart" width="600" height="400"></canvas>
  </div>

  <script>
    var myChart = document.getElementByID('myChart').getContext('2d');

    var spiderChart = new Chart(myChart, {
      type: 'bar',
      data: {
        labels:['Happiness', 'Organization', 'Communication', 'Leader'],
        datasets:[{
            label: 'Statistics',
            data: [10, 20, 55, 30]
          }]
      }
    });
  </script>

</body>
</html>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    简单的 Typeo 问题:)。你应该在document 上使用getElementById 而不是getElementByID

    工作示例:

    var myChart = document.getElementById('myChart').getContext('2d');  // The problem was here
    
        var spiderChart = new Chart(myChart, {
          type: 'bar',
          data: {
            labels:['Happiness', 'Organization', 'Communication', 'Leader'],
            datasets:[{
                label: 'Statistics',
                data: [10, 20, 55, 30]
              }]
          }
        });
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <title>My Chart.js Chart</title>
    </head>
    <body>
      <div class="container">
        <canvas id="myChart" width="600" height="400"></canvas>
      </div>
    
    
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2014-09-11
      • 2015-07-14
      • 2015-04-08
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多