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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With