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>
解决方案
尝试 e.keyCode 而不是 e.keycode
推荐阅读
- lotus-notes - Domino 访问服务 API 出现“无效的通用 ID”错误
- python - 在 Selenium Python 中同时运行两个用户
- scala - 我怎样才能为树状案例类制作编组器?
- javascript - 我想使用 Javascript/Vue 将当前周作为日期数组返回
- c# - 未在 FrameworkElement 上调用 WPF OnRender
- php - 使用 array_filter 删除空子数组值
- flutter - Flutter:如何将列表字符串转换为字符串列表?
- memory-management - 提供给跟踪驱动模拟器的跟踪输入是什么样的?
- react-native - 全新安装时的expo-cli错误
- c# - 从 .Net Core 3.1 调用 WCF BasicBinding 服务