将键盘事件附加到 html5 画布 [英] Attach keyboard events to html5 canvas

查看:19
本文介绍了将键盘事件附加到 html5 画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来 mouse events 可以很好地将监听器添加到 canvas 元素,但 keyboard events 似乎不适用于 画布元素.

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/

浏览器:铬 14.0FF 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).

关于如何在画布元素上监听关键事件有什么想法吗?

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!");
});

另一种有趣的方法是在画布标签上使用 tabIndex 并在画布上绑定按键.我已经更新了 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆