Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener for keydown on Canvas

I am trying to make a canvas app that responds to keyboard and mouse input. I have this code:

canvas = document.getElementById('canvas'); canvas.addEventListener('mousedown', function(event) {     alert('mousedown');         }, false); canvas.addEventListener('keydown', function(event) {     alert('keydown');         }, false); 

The 'mousedown' alert comes up whenever I click the mouse, but the 'keydown' alert never comes up. The same code works fine on JS Bin: http://jsbin.com/uteha3/66/

Why isn't it working on my page? Does canvas not recognize keyboard input?

like image 531
Cbas Avatar asked Oct 14 '12 20:10

Cbas


People also ask

What is addEventListener Keydown?

addEventListener keydown example This example logs the KeyboardEvent. code value whenever you press down a key inside the <input> element. <input placeholder="Click here, then press down a key."

What is the use of Keydown ()?

The keydown() is an inbuilt method in jQuery which is used to trigger the keydown event whenever User presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. So, Using keydown() method we can detect if any key is on its way down.


2 Answers

Set the tabindex of the canvas element to 1 or something like this

<canvas tabindex='1'></canvas> 

It's an old trick to make any element focusable

like image 195
hobberwickey Avatar answered Oct 13 '22 16:10

hobberwickey


Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex attribute on the canvas element (as suggested by hobberwickey).

You can't focus a canvas element. A simple work around this, would be to make your "own" focus.

var lastDownTarget, canvas; window.onload = function() {     canvas = document.getElementById('canvas');      document.addEventListener('mousedown', function(event) {         lastDownTarget = event.target;         alert('mousedown');     }, false);      document.addEventListener('keydown', function(event) {         if(lastDownTarget == canvas) {             alert('keydown');         }     }, false); } 

JSFIDDLE

like image 33
Austin Brunkhorst Avatar answered Oct 13 '22 16:10

Austin Brunkhorst