首页 > 解决方案 > canvas.fillRect 不在浏览器窗口上显示矩形

问题描述

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Archade!</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div style="text-align: center;">
      <canvas id="gameCanvas"></canvas>
    </div>
    <script>
      var canvas;
      var canvasContext;
      window.onload = function () {
        console.log("Game working!");
        canvas = document.getElementById("gameCanvas");
        canvasContext = canvas.getContext("2d");
        canvasContext.fillStyle = "black";
        canvasContext.fillRect(0, 0, canvas.width, canvas.height);
        console.log("Loading red box");
        canvasContext.fillStyle = "red";
        canvasContext.fillRect(500, 500, 50, 25);
        console.log("Red box should be loaded!");
      };
    </script>
  </body>
</html>

这是我的 html 代码,[在 style.css 中我刚刚设置了画布的宽度和高度]。

黑色画布显示在屏幕上,但红色框未显示在任何地方。红色矩形上方和下方的控制台日志也可以正常工作。请帮我解决这个问题!我也希望显示红色矩形。

谢谢你的时间 :)

标签: javascripthtmlcsscanvas

解决方案


从这个参考 - https://www.w3schools.com/tags/canvas_fill.asp

您可以执行以下操作:

  1. 首先绘制矩形。
  2. 然后,设置fillStyle.
  3. 然后填充矩形。

检查下面的代码:

var canvas;
var canvasContext;
window.onload = function() {
  console.log("Game working!");
  canvas = document.getElementById("gameCanvas");
  canvasContext = canvas.getContext("2d");
  canvasContext.rect(0, 0, canvas.width, canvas.height);
  canvasContext.fillStyle = "black";

  canvasContext.fill();
  console.log("Loading red box");

  canvasContext.rect(500, 500, 50, 25);
  canvasContext.fillStyle = "red";
  canvasContext.fill();
  console.log("Red box should be loaded!");
};
<div style="text-align: center;">
  <canvas id="gameCanvas"></canvas>
</div>


推荐阅读