为什么我不能在画布上画一个正方形?

时间:2019-01-20 01:19:37

标签: javascript html5-canvas

嘿,我正在用JS做蛇游戏,现在我要做的就是在画布中央画一条蛇。我已经将画布尺寸设置为木板尺寸,因此一切都可以正确缩放,但是什么都没有显示。任何帮助,将不胜感激:)

//declare global variables
const canvas = document.querySelector('#canvas');

//set canvas context
const ctx = canvas.getContext('2d');

//set canvas dimensions to board dimensions
canvas.width = 768;
canvas.height = 512;

//put canvas dimensions into variables
const cvsW = canvas.width;
const cvsH = canvas.height;

//create snake unit
const unit = 16;

//create snake and set starting position
let snake = [{
	x : cvsW/2,
	y : cvsH/2
}]


ctx.fillStyle = 'limegreen';
ctx.fillRect(snake.x, snake.y, unit, unit);
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Snake</title>
	<style>
		body {
			background-color: #333;
		}

		#canvas {
			background-color: #4d4d4d;
			display: block;
			margin: auto;
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;
		}
	</style>
</head>
<body>
	<canvas id="canvas" width="768" height="512"></canvas>
	<script src="script.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

之所以会这样,是因为您的snake是对象数组。您需要将其变成单个对象以使代码正常工作,或者使用索引在其中选择对象。

ctx.fillRect(snake[0].x-unit/2, snake[0].y-unit/2, unit, unit);

另外,请注意,为了正确地使蛇居中,您需要同时从unit/2x坐标中减去y

您还可以在代码中删除画布尺寸的设置,因为这是在height元素上定义widthcanvas属性时设置的。

请参见下面的工作示例:

//declare global variables
const canvas = document.querySelector('#canvas');

//set canvas context
const ctx = canvas.getContext('2d');

//put canvas dimensions into variables
const cvsW = canvas.width;
const cvsH = canvas.height;

//create snake unit
const unit = 16;

//create snake and set starting position
let snake = [{
  x: cvsW / 2,
  y: cvsH / 2
}];


ctx.fillStyle = 'lime';
ctx.fillRect(snake[0].x - unit / 2, snake[0].y - unit / 2, unit, unit);
body {
  background-color: #333;
}

#canvas {
  background-color: #4d4d4d;
  display: block;
  margin: auto;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}
<canvas id="canvas" width="768" height="512"></canvas>