为什么不能将键码值记录到控制台窗口?

时间:2019-01-14 06:03:05

标签: javascript

嘿,我正在尝试用JS做蛇游戏。现在,我正在制作将确定蛇的方向的函数,但此刻,我只想将任何给定键的键码记录到控制台,但是它是否未定义?为什么是这样?我在登录之前将密钥代码存储到变量中了吗?感谢您的帮助:)

const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');

//set canvas dimension equal to css dimension
canvas.width = 750;
canvas.height = 500;

//create stroke
ctx.strokeStyle = 'limegreen';
ctx.strokeRect(375, 250, 15, 15);

//create square
ctx.fillStyle = 'limegreen';
ctx.fillRect(375, 250, 15, 15);

//read user's direction
document.addEventListener('keydown', changeDirection);

function changeDirection(e) {
	let code = e.keycode;
	console.log(code);
}
<!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 :(得分:2)

尝试使用e.keyCode代替e.keycode