如何为HTML5画布注册onkeydown事件 [英] How to register onkeydown event for HTML5 canvas
问题描述
我想用HTML5 < canvas>
元素编写一个蛇游戏演示。我试图注册键盘(onkeydown)事件,但它不起作用。
I would like to write a snake game demo with HTML5 <canvas>
element. I've tried to register the Keyboard(onkeydown) event, but it's not working.
代码:
canvas.onkeydown = divertDirection; //don't work
//canvas.addEventListener("keydown", divertDirection, false); //don't work
//根据键盘来调振蛇移动的方向
function divertDirection(ev) {
console.log(ev);
}
//register this event for widnow
window.addEventListener("keydown", divertDirection, false); //ok
推荐答案
正如jing3142所说,你可以' t听取不是为它们设计的元素的键盘事件。
As jing3142 has said, you can't listen for keyboard events on elements that are not designed for them.
但是,你可以强制为它们设计一个元素。
However, you can force an element to be designed for them.
canvas.tabIndex = 1000;
现在你可以使用 canvas.addEventListener
了键盘事件。
Now you can use canvas.addEventListener
with keyboard events.
这比 window.addEventListener
更可取,因为那时你不会干扰任何其他元素实际输入元素等页面。
This is preferable over window.addEventListener
because then you don't interfere with any other elements on the page such as actual input elements.
请注意,当画布具有焦点时,您可能会在某些浏览器中看到虚线轮廓。要删除它:
Note that you may see a dotted outline in some browsers when the canvas has focus. To remove this:
canvas.style.outline = "none";
玩得开心!
这篇关于如何为HTML5画布注册onkeydown事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!