It looks like mouse events
will add listeners to canvas
elements fine, but keyboard events
don't seem to be working for canvas
elements.
Example: http://jsfiddle.net/H8Ese/1/
Browsers: Chrome 14.0 FF 5.0.1
I know I can use the document level listeners, but I'm trying to get the Canvas element first (so that your keyboard works everywhere else on the page).
Any ideas on how to get key event listening working on canvas elements?
I don't think you can add keyboard event listener directly to the canvas. If you don't want to register event handler on window level then I think you can wrap the canvas inside a div and register keyboard events on the div.
<div id="canvasWrapper" style="border:1px solid; width:600px; height:400px;">
<canvas id="canvas" width="600" height="400" >
Could not create Canvas!
</canvas>
</div>
jQuery("#canvasWrapper").keypress(function(e){
keys[e.keyCode] = true;
alert("key pressed!");
});
Another interesting way is to use tabIndex on the canvas tag and bind keypress on the canvas. I have updated the code at jsfiddle, pasting here too for future references.
<canvas id="my-canvas" tabindex="1"></canvas>
$("#my-canvas").bind({
keydown: function(e) {
var key = e.keyCode;
var elem=document.getElementById("my-canvas");
var context=elem.getContext("2d");
context.font = "bold 20px sans-serif";
context.clearRect(0,0,300,200);
context.fillText("key pressed " + key, 10,29);
},
focusin: function(e) {
$(e.currentTarget).addClass("selected");
},
focusout: function(e) {
$(e.currentTarget).removeClass("selected");
}
});
$("#my-canvas").focus();