【问题标题】:canvas.fillRect not displaying rectangle on browser window [duplicate]canvas.fillRect 不在浏览器窗口上显示矩形[重复]
【发布时间】:2020-11-22 16:06:39
【问题描述】:

<!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 中我刚刚设置了画布的宽度和高度]。

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

感谢您的宝贵时间 :)

【问题讨论】:

  • 您的画布只有 300x150px 宽,因此坐标 500、500 不在可见区域内。

标签: javascript html css canvas


【解决方案1】:

来自此参考 - 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>

【讨论】:

  • 虽然上述代码确实有效,但如果有人能解释为什么问题中给出的代码无效,那就太好了。
【解决方案2】:

在 css 中设置画布大小可能还不够。 也可以尝试设置画布元素的宽度/高度属性。

例如:

canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;

我认为红色矩形没有显示,因为它的位置超过了画布的默认大小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多