所以这是我的代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Rogue Game</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body onload="canvasGame()">
<canvas id="myCanvas" width="800" height ="800">
<p>Sorry your browser does not support canvas!</p>
</canvas>
</body>
</html>
和Javascript:
function canvasGame() {
canvas = document.getElementById("myCanvas");
if(canvas.getContext) {
ctx = canvas.getContext("2d");
ctx.fillStyle = "white";
ctx.fill();
}
}
我得到的控制台是:
文件:///Users/darceymckelvey/Documents/Rogue/css/style.css 文件:///Users/darceymckelvey/Documents/Rogue/js/main.js 得到 https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js [HTTP / 2.0 304未修改60ms] 文件:///Users/darceymckelvey/Documents/Rogue/css/style.css
我的画布不是白色,只是我在CSS中设置主体的颜色。
答案 0 :(得分:1)
你在脚本中缺少'var'。您也没有任何对象来填充颜色。所以你必须创建一个以填充颜色。有关详细信息,请参阅this documentation on fill()。这是一个有效的例子:
<html>
<head>
<meta charset="utf-8" />
<title>Rogue Game</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body onload="canvasGame()">
<canvas id="myCanvas" width="800" height ="800">
<p>Sorry your browser does not support canvas!</p>
</canvas>
<script>
function canvasGame() {
var canvas = document.getElementById("myCanvas");
if(canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.fillStyle = "white";
ctx.fill();
}
}
</script>
</body>
</html>