如何修复“无法读取null的属性'getContext'”错误?让ctx = canvas.getContext(“ 2d”)

时间:2019-12-12 13:02:05

标签: javascript html null

这是给我问题的代码,特别是“ let ctx = canvas.getContext(“ 2d”);“行。我一直在阅读类似我的类似问题的解决方案,但似乎都没有帮助。

index.js

import Paddle from "/src/paddle.js";

let canvas = document.getElementById("gameScreen")
let ctx = canvas.getContext("2d");

const GAME_WIDTH = 800;
const GAME_HEIGHT = 600

let paddle = new Paddle(GAME_WIDTH, GAME_HEIGHT);

paddle.draw(ctx);

let lastTime =0;

function gameLoop(timestamp){
    let deltaTime = timestamp - lastTime;
    lastTime = timestamp;

    ctx.clearRect(0, 0, 800, 600);
    paddle.update(deltaTime);
    paddle.draw(ctx);

    requestAnimationFrame(gameLoop);
}

gameLoop();

index.html

<html>
  <head>
    <title>Space Invaders</title>
    <meta charset="UTF-8" />
    <style>
      #gameScreen {
        border: 1px solid black;
      }
    </style>
  </head>

  <body>
      <h1>Please stop giving me errors</h1>
    <canvas id="gameScreen" width="800" height="600"></canvas>

    <script src="src/index.js"></script>
  </body>
</html>

2 个答案:

答案 0 :(得分:0)

我建议将所有代码包装在index.js内的window.onload

// index.js

import Paddle from "/src/paddle.js";

window.onload = function() {
  let canvas = document.getElementById("gameScreen");
  ....
  gameLoop();
}

答案 1 :(得分:0)

这样写代码解决了我的问题

"use strict";

class Paddle {
  constructor(gameWidth, gameHeight) {
    this.width = 150;
    this.height = 20;

    this.position = {
      x: gameWidth / 2 - this.width / 2,
      y: gameHeight - this.height - 10
    };
  }
  draw(ctx) {
    ctx.fillStyle = "#0ff";
    ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
  }

  update(deltaTime) {
    if (!deltaTime) return;

    this.position.x += 5 / deltaTime;
  }
}

(function() {
  let canvas = document.getElementById("gameScreen");
  let ctx = canvas.getContext("2d");

  const GAME_WIDTH = 800;
  const GAME_HEIGHT = 600;

  let paddle = new Paddle(GAME_WIDTH, GAME_HEIGHT);

  paddle.draw(ctx);

  let lastTime = 0;

  function gameLoop(timestamp) {
    let deltaTime = timestamp - lastTime;
    lastTime = timestamp;

    ctx.clearRect(0, 0, 800, 600);
    paddle.update(deltaTime);
    paddle.draw(ctx);

    requestAnimationFrame(gameLoop);
  }

  gameLoop();
})();