Javascript:我的画布没有绘制任何内容

时间:2016-01-19 17:08:56

标签: javascript html5-canvas

我正在制作一个基本的游戏循环,所以我从基本的立方体练习开始,我在下面编写了例子,但它不起作用。我试图看看是否有拼写错误,但我什么都找不到。

<!DOCTYPE HTML>
<html>
<head>
<title>Game</title>
<style type="text/css">
#GameCanvas {
   background-color: #FF0000;
}
</style>
</head>
<body>
<canvas id="GameCanvas" width="1000" height="600"></canvas>
<script type="text/javascript">
var canvas = document.findElementById("GameCanvas");
var graphics = canvas.getContext("2d");
function Update() {}
function Draw() {
graphics.beginPath();
graphics.fillRect(20, 20, 50, 50);
graphics.fillStyle = "#FFFFFF";
graphics.fill();
graphics.closePath();
}
function GameLoop() {
Update();
Draw();
requestAnimFrame(GameLoop);
}
requestAnimFrame(GameLoop);
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

此处有几个错误,document.findElementById不存在,请将其更改为document.getElementById

在两种情况下,

requestAnimFrame都应更改为requestAnimationFrame

通过这些更改,您的循环将运行并在屏幕上绘制一个方块。

<!DOCTYPE HTML>
<html>
<head>
<title>Game</title>
<style type="text/css">
#GameCanvas {
   background-color: #FF0000;
}
</style>
</head>
<body>
<canvas id="GameCanvas" width="1000" height="600"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("GameCanvas");
var graphics = canvas.getContext("2d");
function Update() {}
function Draw() {
  graphics.beginPath();
  graphics.fillRect(20, 20, 50, 50);
  graphics.fillStyle = "#FFFFFF";
  graphics.fill();
  graphics.closePath();
}
function GameLoop() {
  Update();
  Draw();
  requestAnimationFrame(GameLoop);
}
requestAnimationFrame(GameLoop);
</script>
</body>
</html>