将键盘事件附加到html5画布 [英] attach keyboard events to html5 canvas
问题描述
看起来鼠标事件
会将侦听器添加到 canvas
元素,但是键盘事件
似乎不适用于 canvas
元素。
It looks like mouse events
will add listeners to canvas
elements fine, but keyboard events
don't seem to be working for canvas
elements.
示例:
http://jsfiddle.net/H8Ese/1/
浏览器:
Chrome 14.0
FF 5.0.1
Browsers: Chrome 14.0 FF 5.0.1
我知道我可以使用文档级别的侦听器,但我正在尝试首先获取Canvas元素(这样你的键盘就可以在页面的其他地方工作)。
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).
关于如何在canvas元素上进行关键事件监听的任何想法?
Any ideas on how to get key event listening working on canvas elements?
推荐答案
我认为你不能直接在画布上添加键盘事件监听器。如果您不想在窗口级别注册事件处理程序,那么我认为您可以将画布包装在div中并在div上注册键盘事件。
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!");
});
另一个有趣的方法是在canvas标签上使用tabIndex并在画布上绑定keypress。我已经更新了jsfiddle的代码,也粘贴在这里以供将来参考。
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();
这篇关于将键盘事件附加到html5画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!