A lot of people have posted on the net about not being able to get key events on canvas. It turns out that it's not very hard and I'm going to show you how.
The problem is that canvas isn't a normal place that the browser expects you to type in, so it doesn't have the focus. Having the focus means that you are the element that key events get handed to. Usually you tell the browser which text element gets the focus by clicking on it or by hitting the <TAB> key until the right element gets a box highlighted around it to tell you it's active. You can try clicking and tabbing if you want, but you might as well save the effort, it won't work.
So if the problem is that the canvas doesn't get the focus, what about if we do,
If you want, you can click the button and it will run that line for you and then you can try it.
But -- unfortunately it still won't work. What gives? Well, canvas1 is defined like this
Now we're going to create a new canvas, canvas2 and the only difference will be that we will set a tabindex for it.
With this canvas you'll be able to click on it or tab to it and then press a key. An alert will pop up telling you the keycode. From javascript you'll also be able to give the focus to it if you want to.
At times, you might want to give the focus without clicking or tabbing. You want it to work if you just put the mouse over the canvas. The trick there is to give a mouseover handler to the canvas, and in the mouseover handler give the focus to the canvas. If you want you can also give a mouseout handler to the canvas and in there take away the focus with blur(). I'll create a canvas3 that works like that. Here's the canvas and the code.
We can give it a tabindex after the fact like this.
Just click the button and then canvas1 will get the focus. He'll start receiving the keydown events right away.
So, just to summarize, if you want to get information about keys in a canvas, make sure that you give it a tabindex, and then it will work just like any other element. You'll be able to use any of the key events, and it will work just like you want. Good coding!