如何修复测试Canvas代码时出现的"TypeError: Cannot set property 'width' of null"错误?
Hey Albert, let's get that canvas error sorted out! That Uncaught TypeError: Cannot set property 'width' of null message is telling you that your JavaScript is trying to modify a canvas element that doesn't exist (yet) when the code runs. Here's why it's happening and how to fix it:
Why this error occurs
Your JavaScript code runs the second the browser parses it, but in your current code, the <canvas id="sim00"> element comes after the JS. So when document.getElementById("sim00") executes, the browser hasn't created that canvas element yet—hence it returns null, and trying to set null.width throws the error.
Fix 1: Move your JS below the canvas element
The simplest fix is to rearrange your code so the script runs after the canvas is defined in the DOM. I also fixed your CSS (it needs to be inside a <style> tag to work):
<canvas id="sim00" width="300" height="300"></canvas> <style> canvas { border: 1px solid #d3d3d3; max-width: 100%; height: auto; } </style> <script> var canvas = document.getElementById("sim00"); var dim = { w: 600, h: 480 }; canvas.width = Math.min(dim.w, window.innerWidth - 20); canvas.height = Math.min(dim.h, window.innerHeight - 20); </script>
Fix 2: Wait for the DOM to fully load
If you need to keep your JS in the <head> or before the canvas element, wrap your code in a DOMContentLoaded event listener. This ensures your code only runs once all elements in the page are ready:
document.addEventListener('DOMContentLoaded', function() { var canvas = document.getElementById("sim00"); var dim = { w: 600, h: 480 }; canvas.width = Math.min(dim.w, window.innerWidth - 20); canvas.height = Math.min(dim.h, window.innerHeight - 20); });
Just drop this script anywhere in your page (even the <head>) and it will work correctly.
Quick reminder about your CSS
Raw CSS code floating outside a <style> tag or external stylesheet won't be applied to your elements—always wrap it in a <style> block like I did in Fix 1, or link to an external .css file.
内容的提问来源于stack exchange,提问作者Albert

