javascript - 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 中我刚刚设置了画布的宽度和高度]。
黑色画布显示在屏幕上,但红色框未显示在任何地方。红色矩形上方和下方的控制台日志也可以正常工作。请帮我解决这个问题!我也希望显示红色矩形。
谢谢你的时间 :)
解决方案
从这个参考 - https://www.w3schools.com/tags/canvas_fill.asp
您可以执行以下操作:
- 首先绘制矩形。
- 然后,设置
fillStyle
. - 然后填充矩形。
检查下面的代码:
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>
推荐阅读
- r - 在 dplyr 的函数中使用预先存在的值
- c# - C# 我在 Ubuntu 中遇到 MemoryMappedFiles 的问题
- reactjs - 无法读取未定义的“某些”属性
- python - 如何根据python中多列的值填充一列?
- bash - 用于从 netezza 到 linux 服务器目录的历史加载的 Bash 脚本
- excel - IF 公式返回 FALSE
- autodesk-forge - 从 Forge 查看器中的捕捉点检索坐标
- angular - 从一个页面刷新到另一个页面 ionic
- reactjs - 在 heroku 和 react 应用程序上设置 http 基本身份验证
- python - 无论实际内容如何,sklearn 文本分类模型都返回单个类