<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body>
<canvas id="GameArea"></canvas>
<script>
var myGamePiece;
myGamePiece = new component(30, 30, "red", 10, 120);
function component(width, height, color, x, y) {
console.log("component called");
this.width = width;
this.height = height;
this.x = x;
this.y = y;
var myGameArea=document.getElementById("startGame");
console.log("myGameArea");
var ctx = myGameArea.getContext("2d");
console.log("crossed");
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
</script>
<p>We have added a component to our game, a red square!</p>
</body>
</html>
//无法解决我的错误 在上面的代码中,我尝试在调用一些名为component的函数时创建一个矩形。 它按上下文创建了一个矩形但我收到了错误
答案 0 :(得分:0)
您的画布的ID为&#34; GameArea&#34;,但您正在尝试执行getElementById(&#34; startGame&#34;)。
答案 1 :(得分:0)
您的canvas元素ID是“GameArea”,但您在代码中称为“startGame”。这就是它为空的原因