javascript - 无法在画布上绘制正方形
问题描述
嘿伙计们,我正在用 JavaScript 开始一个蛇游戏。现在我要做的是在画布的中心画一个绿色的小方块。我已经设置了 fillStyle 并使用了 fillRect 方法,但我什么也没得到。谁能解释一下这个问题,我真的很感激,谢谢:)
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'limegreen';
ctx.fillRect(375, 250, 10, 10);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
body {
background-color: #333;
}
canvas {
background-color: #4d4d4d;
margin: auto;
display: block;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 750px;
height: 500px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>
解决方案
看起来您的画布尺寸太小(即默认尺寸为 300w x 150h),这意味着绿色矩形绘制在画布尺寸之外的 [375,250] 处。
尝试如下设置画布的width
和height
属性(即匹配您的样式):
canvas.width = 750;
canvas.height = 500;
这将确保画布分辨率/尺寸设置得当,使矩形可见。
关键是:画布有自己的尺寸概念。这些不是从应用于画布的任何 CSS 样式继承的。
这是一个工作片段:
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
// Necessary to specify the resolution of the canvas
// explicitly by doing this:
canvas.width = 750;
canvas.height = 500;
ctx.fillStyle = 'limegreen';
ctx.fillRect(375, 250, 10, 10);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
body {
background-color: #333;
}
canvas {
background-color: #4d4d4d;
margin: auto;
display: block;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 750px;
height: 500px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>
推荐阅读
- reactjs - React useState如何修改数组中的第一个对象
- arrays - 如何在 Powershell 中按对象的一个属性值对对象数组进行排序?
- c# - 仅序列化类的集合
- python - 如何将文件或图像作为 Keras 模型中的参数提供给 model.predict?
- python - 我试图制作一个 Python 时钟,但我无法让它循环
- ruby-on-rails - 如何在创建操作中调用 Select_tag
- components - 上层实体期待“输入”引脚,而下层实体正在使用“输出”引脚
- python - 如何在 docsify.js 上使用深色主题、翻译和搜索?
- angular - Angular/angularfire2 - 读取可观察的文档并将数据保存到对象。没有异步管道
- php - 电子邮件在本地主机和服务器上发送,但邮件未到达服务器