You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错Cannot read properties of null (reading 'getContext')的原因是什么?

Fixing "Cannot read properties of null (reading 'getContext')" Error

Let's break down why this error pops up and walk through how to fix it:

Common Causes

  • ID Typo Mismatch: Looking at your code, there's a small but critical spelling error! In JavaScript, you're targeting gameSecreen (extra 'e' between 's' and 'c'), but your canvas element has the ID gameScreen. When getElementById can't find a matching element, it returns null—and trying to call getContext on null throws this exact error.
  • Code Runs Before DOM Loads: Browsers parse HTML top to bottom. If your JavaScript executes before the browser has loaded the <canvas> element, document.getElementById will also return null. This happens if your script is placed above the canvas tag in your HTML.

Step-by-Step Solutions

1. Fix the ID Spelling First

Correct the ID in your JavaScript to match the canvas element perfectly:

// Change "gameSecreen" to "gameScreen"
let canvas = document.getElementById("gameScreen");

2. Ensure JavaScript Runs After the Canvas Exists

Pick one of these methods to guarantee your code only runs once the canvas is loaded:

Option A: Move Script to After the Canvas

Place your <script> tag right after the canvas element. This way, the browser parses the canvas first before executing your JS:

<canvas id="gameScreen" width="800" height="600"></canvas>
<script>
let canvas = document.getElementById("gameScreen");
let ctx = canvas.getContext("2d");
ctx.fillRect(20, 20, 100, 100);
</script>

Option B: Wrap Code in DOMContentLoaded Event

Use this event listener to trigger your code only when all DOM elements are fully loaded:

document.addEventListener('DOMContentLoaded', function() {
  let canvas = document.getElementById("gameScreen");
  let ctx = canvas.getContext("2d");
  ctx.fillRect(20, 20, 100, 100);
});

Option C: Add the defer Attribute to Your Script

If your script is in an external file or inline, adding defer tells the browser to load the script but delay execution until the DOM is parsed:

<script defer>
let canvas = document.getElementById("gameScreen");
let ctx = canvas.getContext("2d");
ctx.fillRect(20, 20, 100, 100);
</script>

Quick Verification

After applying these fixes, your code should successfully grab the canvas element, access its 2D context, and draw the rectangle as intended.

内容的提问来源于stack exchange,提问作者Jakob QN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:34:05