【发布时间】:2019-11-21 15:48:57
【问题描述】:
我正在尝试制作画布的背景,但我无法使用 getContext。我得到错误:
Uncaught TypeError: Cannot read property 'getContext' of null at game.js:4
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
const canvas = document.getElementById('canvas');
if (canvas != null) {
ctx = canvas.getContext("2d");
} else {
console.log('wtf happen');
}
function draw(){
ctx.background(255,0,0);
}
我已经尝试过使用帖子:Cannot read property 'getContext' of null
但这对我没有帮助。
【问题讨论】:
-
您的 JavaScript 与 DOM 元素的关系在哪里?我的猜测是你的 javascript 在 DOM 元素存在之前就已经运行了。你应该把你的 JS 放在结束的
标签: javascript html