报错Cannot read properties of null (reading 'getContext')的原因是什么?
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 IDgameScreen. WhengetElementByIdcan't find a matching element, it returnsnull—and trying to callgetContextonnullthrows 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.getElementByIdwill also returnnull. 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

