我得到的错误空

问题描述:

无法读取property'get语境”
<!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> 

//不能在上面的代码中,我试图在调用名为组件一些函数来创建一个矩形getout我的错误 的。 它创建上下文的长方形,但我得到一个错误我得到的错误空

+2

请学会自己调试你的代码。阅读错误信息并尝试理解它。 'startGame'和'GameArea'不一样。 – Xufox

你的画布,具有“GameArea”的ID,但你正在试图做的getElementById(“startGame”)。

您的画布元素ID是“GameArea”,但您在代码中称为“startGame”。这就是为什么它是空的