【发布时间】:2020-11-16 07:33:00
【问题描述】:
我正在尝试制作 HTML、CSS 和 JavaScript 游戏。当按下左右箭头键时,玩家应该左右移动。我不知道为什么,但这段代码没有添加事件监听器。有什么帮助吗?这是我的 index.html 文件中的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
JavaScript Platformer
</title>
</head>
<body>
<canvas id="game" class="game" width="500" height="500"></canvas>
</body>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
</html>
这是我的 script.js 文件中的代码:
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
var playerImg = new Image();
var player = {
x: 225,
y: 375,
width: 50,
height: 50
}
function draw() {
playerImg.onload = function () {
// draws the player image
ctx.drawImage(playerImg, player.x, player.y, player.width, player.height);
}
playerImg.src = "images/player.png";
}
document.body.addEventListener("keydown", function (event) {
event.preventDefault();
if (event.keycode == 37) {
// deletes the last image so the image doesn't get duplicated
ctx.clearRect(player.x, player.y, player.x + player.width, player.y + player.height);
// moves the player
player.x -= 20;
}
if (event.keycode == 39) {
// deletes the last image so the image doesn't get duplicated
ctx.clearRect(player.x, player.y, player.x + player.width, player.y + player.height);
// moves the player
player.x -= 20;
}
}, false);
setInterval(draw, 100);
这是我的 CSS 文件中的代码:
.game {
border: 3px solid black;
border-radius: 8px;
}
有什么帮助吗?我看不出这段代码有什么问题。
【问题讨论】:
-
您是否尝试过调试代码以查看事件是否正在触发,以及它认为已按下的键码是否为?
-
请使用 keyCode 而不是 keycode。一定有错别字。在更正您的错字后,我确认它可以正常工作。
-
请在右箭头键事件中将您的代码更新为
player.x += 20;(keyCode: 39) -
KeyboardEvent.keyCode是一个折旧的属性developer.mozilla.org/en-US/docs/Web/API/…,你不应该使用它。使用KeyboardEvent.code或KeyboardEvent.key
标签: javascript html css html5-canvas event-listener