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

.fillStyle not working, no errors in console

本文关键字:有错误 控制台 不起作用 fillStyle      更新时间:2023-09-26

这是我的代码:

<!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();
  }
}

我得到的控制台是:

file:///Users/darceymckelvey/Documents/Rogue/css/style.cssfile:///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]file:///Users/darceymckelvey/Documents/Rogue/css/style.css

我的画布不是白色的,它只是我在 CSS 中设置身体的颜色。

脚本中缺少"var"。您也没有任何对象要填充颜色。因此,您必须创建一个才能用颜色填充它。有关详细信息,请参阅有关 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>