addEventListener keydown not working
29,120
Solution 1
You can't assign the keydown
event to the canvas because you can't focus the canvas with the cursor. You will need to assign the event to the window:
window.addEventListener("keydown", handle, true);
Solution 2
You can try to replace canvas with window.
Author by
JBurace
Updated on July 29, 2022Comments
-
JBurace over 1 year
I took some basic Pong code available on the internet and tried to add keypresses, the code is here: http://cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds
I added this:
canvas.addEventListener("keydown", handlekeydown, true);
After this existing code:
canvas.addEventListener("mousemove", trackPosition, true); canvas.addEventListener("mousedown", btnClick, true);
And I also added this:
function handlekeydown(e) { console.log("debug"); console.log("keycode: "+e.keyCode); }
But the function is never called even though I try pressing various keys. Why is this? I'm pretty sure the Canvas is in focus.