不能在画布上画正方形

时间:2019-01-14 04:30:27

标签: javascript html

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

1 个答案:

答案 0 :(得分:1)

您的画布尺寸似乎太小(即默认尺寸为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>