未为简单图表定义画布

时间:2018-10-10 13:29:47

标签: javascript chart.js

我正在尝试在我的网站上放置一个简单的图表。我有以下代码:

<script src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script>
var ctx = canvas.getContext("2d");
var parent = document.getElementById('parent');
canvas.width = parent.offsetWidth;
canvas.height = parent.offsetHeight;

var chart = new Chart(ctx, {
  type: 'line',
  options: {
      legend: {
      display: false
    },
    responsive: true,
    maintainAspectRatio: false
  },
  data: {
    labels: [3,4],
    datasets: [{
        label: 'Test 01',
        data: [1,2],
      }
    ]
  }
});
</script>
<div id="parent">
  <canvas id="myChart"></canvas>
</div>

但是它会向我返回错误:

Uncaught ReferenceError: canvas is not defined
    at mytest3.html:47

我尝试将画布移动到脚本的上方和下方,但这没有什么不同。我在这里做什么错了?

3 个答案:

答案 0 :(得分:1)

您需要先设置canvas变量,然后才能使用它。添加以下内容:

<script>
//Add the following line
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");

答案 1 :(得分:1)

您还需要像 var canvas = document.getElementById('myChart')

答案 2 :(得分:1)

您需要在元素存在之后放置脚本。您需要定义画布。...

<script src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<!-- Need to put canvas before the script -->
<div id="parent">
  <canvas id="myChart"></canvas>
</div>
<script>
var canvas = document.getElementById("myChart");  // <-- need to define canvas
var ctx = canvas.getContext("2d");
var parent = document.getElementById('parent');
canvas.width = parent.offsetWidth;
canvas.height = parent.offsetHeight;

var chart = new Chart(ctx, {
  type: 'line',
  options: {
      legend: {
      display: false
    },
    responsive: true,
    maintainAspectRatio: false
  },
  data: {
    labels: [3,4],
    datasets: [{
        label: 'Test 01',
        data: [1,2],
      }
    ]
  }
});
</script>