Home > Back-end >  Key detection problem in JavaScript. What is wrong with my function?
Key detection problem in JavaScript. What is wrong with my function?

Time:06-13

So I want to create a basic RPG (with extremely bad graphics) and the following code for detecting the up arrow key doesn't work... Any suggestions? (note that I'm a n00bie)

document.onkeydown = event => {
    ctx.fillStyle = "red";

    if (event.key == (keyCode == '38')) {
        height -= 25;
        ctx.clear();
        ctx.fillRect(width, height, 25, 50);
    }

I'm gonna send the fiddle here: https://jsfiddle.net/xedra6bn/ As you can see I haven't done the other arrow keys so don't try them as a test.

CodePudding user response:

Okay, so you have not created a Clear function, and your console is showing an error, and your if statement should be a little bit different. So:

document.onkeydown = event => {
    ctx.fillStyle = "red";

    if (event.keyCode == '38')//change your if statemment like this {
        height -= 25;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillRect(width, height, 25, 50);
    }

CodePudding user response:

Check the key code like this:

if (event.keyCode === 38) {
    // some code
}

EDIT

keyCode is deprecated. You can use key:

if (event.key === 'ArrowUp') {
    // some code
}
  • Related