[英]Property 'getContext' does not exist on type ''HTMLElement"
I am trying to make the background of the canvas but I can't use getContext. 我试图制作画布的背景但我不能使用getContext。 I get the error:
我收到错误:
Uncaught TypeError: Cannot read property 'getContext' of null at game.js:4 未捕获的TypeError:在game.js:4中无法读取null的属性'getContext'
Html HTML
<!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8">
<title>Game</title>
</head>
<body>
<script src="game.js"></script>
<canvas id="canvas" width="100" height="320"></canvas>
</body>
</html>
Javascript 使用Javascript
const canvas = document.getElementById('canvas');
if (canvas != null) {
ctx = canvas.getContext("2d");
} else {
console.log('wtf happen');
}
function draw(){
ctx.background(255,0,0);
}
I have already tried using the post: Cannot read property 'getContext' of null 我已经尝试过使用帖子: 无法读取null的属性'getContext'
but it did not help me. 但它没有帮助我。
This is because you are calling your javascript before the element is added to the page/DOM and the browser runs/loads code/HTML synchronously (one line at a time). 这是因为您在将元素添加到页面/ DOM之前调用了javascript,并且浏览器同步运行/加载代码/ HTML(一次一行)。
So, this leaves us with three options: 所以,这给我们留下了三个选择:
Add defer to your script tag this will load it after the dom is ready 添加defer到您的脚本标记,这将在dom准备好后加载它
<script src="game.js" defer></script>
Moving the tag after the canvas will allow the canvas to be ready when the script runs 在画布之后移动标记将允许在脚本运行时准备好画布
<canvas id="canvas" width="100" height="320"></canvas>
<script src="game.js"></script>
Putting your code within this event will run the code after the DOM has loaded. 将代码放在此事件中将在DOM加载后运行代码。
document.addEventListener('DOMContentLoaded', e => {
const canvas = document.getElementById('canvas');
if (canvas != null) {
ctx = canvas.getContext("2d");
} else {
console.log('wtf happen');
}
function draw(){
ctx.background(255,0,0);
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.