Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Key detection problem in JavaScript. What is wrong with my function?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading