Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener keydown not working

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.

like image 304
JBurace Avatar asked Mar 26 '13 21:03

JBurace


Video Answer


1 Answers

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);
like image 182
Jean Lourenço Avatar answered Sep 30 '22 00:09

Jean Lourenço