为什么我的画布无法正常工作并出现?

时间:2019-12-31 01:30:51

标签: javascript html canvas html5-canvas syntax-error

问题 最近,我在youtube上观看了一个制作迷你蛇游戏的教程。我完全找到了它,但是我的chrome(ver.79)告诉我我遇到了错误。下面是代码和错误消息。

代码

<canvas width="600px" height="500px" /canvas>
<script>
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  function drawRect(x, y, color) {
    var size = 20;
    var padding = 2;
    ctx.beginPath();
    ctx.rect((size + padding) * x, (size + padding) * y, size, size);
    ctx.fill();
  }
  var tableSize = 10;
  class User {
    x = 0;
    y = 0;
    // color = 000;
    dire = 2;
    tailList = [];
    update() {
      switch (this.dire) {
        case 0:
          this.x -= 1;
          break;
        case 1:
          this.y -= 1;
          break;
        case 2:
          this.x -= 1;
          break;
        case 3:
          this.y -= 1;
          break;
      }
      this.x = this.loop(this.x);
      this.y = this.loop(this.y);
    }
    addTail() {
      this.tailList.push({ x: this.x, y: this.y });
    }
    loop(value) {
      if (value < 0) {
        value = tableSize - 1;
      } else if (value > tableSize - 1) {
        value = 0;
      }
      return value;
    }
  }
  class Item {
    x = 0;
    y = 0;
    color = "#00f";
    randomPosition() {
      this.x = parseInt(Math.random() * tableSize);
      this.y = parseInt(Math.random() * tableSize);
    }
  }
  var user = new User();
  var item = new Item();
  item.randomPosition();
  setInterval(function() {
    for (var x = 0; x < tableSize; x++) {
      for (var y = 0; y < tableSize; y++) {
        drawRect(x, y, "#eee");
      }
    }
    user.update();
    if (user.x == item.x && user.y === item.y) {
      user.addTail();
      item.randomPosition();
    }
    for (var i in user.tailList) {
      var p = user.tailList[i];
      drawRect(p.x, p.y, user.color);
    }
    drawRect(user.x, user.y, user.color);
    drawRect(item.x, item.y, item.color);
  }, 200);
  window.onkeydown = function(e) {
    if (e.keyCode >= 37 && e.keyCode <= 40) {
      user.dire = e.keyCode - 37;
    }
  };
</script>

错误

  

game_snake.html:4未捕获的TypeError:无法读取属性   'getContext'为null       在game_snake.html:4

var ctx = canvas.getContext("2d");

0 个答案:

没有答案