I have an image here, and it is in an canvas, however pressing the designated key causes nothing to happen. Where did my code go wrong?
let img = document.getElementById("ship");
let player = {
x: 375,
y: 550,
w: 50,
h: 50,
};
requestAnimationFrame(draw);
function draw() {
//Logic
ctx.drawImage(img, player.x, player.y, player.w, player.h);
//Draw
ctx.clearRect(0, 0, cnv.width, cnv.height);
requestAnimationFrame(draw);
}
document.addEventListener("keydown", move);
function move(event) {
console.log(event.code);
if (event.code === 39) {
player.x = player.x + 50;
} else if (event.code === 37) {
player.x = player.x - 50;
} else if (event.code === 40) {
player.x = player.y - 50;
} else if (event.code === 38) {
player.x = player.y + 50;
}
}
The type of event.code
is a DOMString and not a number as event.keyCode
.
eg: pressing left arrow will verify event.keyCode === 37
and event.code === 'ArrowLeft'
.
Change either code
to keyCode
, or the values against which you check event.code
and you should be good to go:)
Cheers!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.