Keyboard input and canvas

Hello, there I have been developing a canvas game lately that needs keyboard input (it's a platformer after all). I follow the w3schools game tutorial that has keyboard input in it. I don't see get how they got keyboard input working, I want an easy way to access it like a class, object or something else that allows me to get easy keyboard input. here is the game loop code: setInterval(function() { // clear the canvas can.clear() // sx = speed x | slow down the player player.sx = 0 //here i want the keyboard handler //update and render the player player.update() },10) edit: I know that you can add key down/up event listeners, and I searched Sololearn for "canvas keyboard"

1/19/2020 5:50:46 PM

dan Gameing

2 Answers

New Answer


When you're searching for help on this, you can drop the "canvas" aspect of your search since what you're outputting graphics to has nothing to do with how you get keyboard input. You probably want to listen for keypress or keydown events. I would bind an event listener to the document instead of any little element in a specific part of the page. Keyboard input events are fired only on focused elements but they usually bubble up so listening on the document as a whole is more likely to work. It would be annoying if accidentally clicking a random part of the page caused your game to ignore keyboard input. Here is an example taken from https://stackoverflow.com/questions/17015019/keylistener-in-javascript: document.addEventListener('keyup', (e) => { if (e.code === "ArrowUp") player.sx ++; else if (e.code === "ArrowDown") player.sx --; }); For a couple web apps I wrote, I wanted people to hold shift while doing mouse events to express different things. For this, you could use MouseEvent's which property. One of these examples is at: https://code.sololearn.com/WvW556P3kzwK Your display will refresh often enough that there's no reason to have your keyboard listener call can.clear() or player.update(). Let the other loop you shared do that. There is more information on w3schools about this: https://www.w3schools.com/jsref/event_onkeypress.asp If you want a more official API documentation instead of a tutorial, see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent MouseEvent's which property is documented at: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent On an unrelated note, consider using https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame instead of setTimeout for your display loop. That function is closer to your intended purpose than setTimeout.


is there like a way to do something like this? if (keyboard.down == 87) { console.log("you pressed W!") }