首页 > 解决方案 > 无法在画布上绘制正方形

问题描述

嘿伙计们,我正在用 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>

标签: javascripthtml

解决方案


看起来您的画布尺寸太小(即默认尺寸为 300w x 150h),这意味着绿色矩形绘制在画布尺寸之外的 [375,250] 处。

尝试如下设置画布的widthheight属性(即匹配您的样式):

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>


推荐阅读