如何为 HTML5 画布注册 onkeydown 事件 [英] How to register onkeydown event for HTML5 canvas
问题描述
我想用 HTML5 <canvas>
元素编写一个蛇游戏演示.我尝试注册 Keyboard(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 所说,你不能在不是为它们设计的元素上监听键盘事件.
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屋!