Here’s a very simple thing I’d like to do: when the pointer is within a canvas element and I press, say, the key ‘A’ I want to draw a circle centered at the given location. Alas, I can’t seem to be able to achieve this. I know how to add a listener to capture mouse click events:
var canvas = goog.dom.getElement('my_canvas');
goog.events.listen(canvas, [goog.events.EventType.CLICK],
function(e) {console.log(e);});
Easy es pie and works beautifully: the event has the coordinates of where I clicked so I can use it to draw a circle. But I wanted to use the keyboard for this (because I’m planning on having other actions as well). First, I tried the trivial:
goog.events.listen(canvas, [goog.events.EventType.KEYDOWN],
function(e) {console.log(e);});
Nothing. I tried, using KEYUP, KEYPRESS, or all of them together: not a beep. Then, I came across goog.events.KeyHandler and tried that. Here’s what I did:
var canvas = goog.dom.getElement('my_canvas');
var keyHandler = new goog.events.KeyHandler(canvas);
goog.events.listen(keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) {console.log(e);});
Still nothing. Now, I got angry, so I said “Let’s see if we can capture any keyboard events at all!” and did the following:
var keyHandler = new goog.events.KeyHandler(document);
goog.events.listen(keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) {console.log(e);});
Lo and behold, it worked: now I was capturing all keyboard events. Unfortunately, when I looked at the events in the javascript console, the keyboard events didn’t have any coordinates or even target elements in them. What? I mean, that’s not very useful, right?
Anyhow, I’m stuck. It seemed like a trivial thing to do but I can’t seem to be able to do it.
I’m using Chrome Version 19.0.1084.53 on Mac OS X Version 10.7.4.
I’m not sure about the version of Closure I’m using (how do you even find it out?) because I’m using Plovr which comes bundled with its Closure version, but I believe it’s pretty recent (Feb 2012).
OK, as pointed out by cpeisert in the comment, the problem was that canvas, by default, cannot get the input focus. I had to add ‘tabindex=”1″‘ to make it happen. Next, I had to surround canvas with a div and attach my event handler to the div.
Related Question (although not using Closure)