我正忙着完成这个使用Javascript和canvas元素创建2D游戏的tutorial,我遇到了两个错误。
我的初始代码是:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Game Canvas Workshop</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id"myCanvas" width="480" height="320"></canvas>
<!-- <script type="text/javascript" src="../game.js"></script> -->
<script>
//var test = document.getElementsByTagName("canvas");
//console.log(test);
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
console.log(ctx);
ctx.beginPath();
ctx.rect(20, 40, 50, 50);
ctx.fill();
ctx.closePath();
</script>
</body>
</html>
当我尝试使用document.getElementById
抓取canvas元素时,它会返回错误:canvas is null
所以我更改了代码以使用document.getElementsByTagName
获取canvas元素,然后编写了一个测试来将结果打印到控制台并返回元素。
但是当我尝试使用canvas.getContext("2d")
时,我收到以下错误:canvas.getContext("2d") is not a function
我已经阅读了类似查询的大部分答案,并尝试使用我的代码,但它们似乎并不适合我。
请帮忙。
答案 0 :(得分:0)
你需要
<canvas id="myCanvas" width="480" height="320"></canvas>
^
id的作业。
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//console.log(ctx);
ctx.beginPath();
ctx.rect(20, 40, 50, 50);
ctx.fill();
ctx.closePath();
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
<canvas id="myCanvas" width="480" height="320"></canvas>
答案 1 :(得分:0)
Please load your <script> after <body>. then this would work.
<body>
<input type="text" id="myInput" >
<canvas id="myCanvas" width="200" height="100"></canvas>
</body>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
</script>
答案 2 :(得分:0)
问题在这里(缺少&#34; =&#34;)
<canvas id"myCanvas" width="480" height="320"></canvas>
更改为:
<canvas id="myCanvas" width="480" height="320"></canvas>
完整代码
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Game Canvas Workshop</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<!-- <script type="text/javascript" src="../game.js"></script> -->
<script>
//var test = document.getElementsByTagName("canvas");
//console.log(test);
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
console.log(ctx);
ctx.beginPath();
ctx.rect(20, 40, 50, 50);
ctx.fill();
ctx.closePath();
</script>
</body>
</html>