gpt4 book ai didi

javascript - .fillStyle 不起作用,控制台中没有错误

转载 作者:行者123 更新时间:2023-11-27 23:03:39 26 4
gpt4 key购买 nike

这是我的代码:

<!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

我的 Canvas 不是白色的,它只是我在 CSS 中设置主体的颜色。

最佳答案

您在脚本中缺少“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>

关于javascript - .fillStyle 不起作用,控制台中没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814589/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com