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.
Code:
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
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;
Now you can use canvas.addEventListener
with keyboard events.
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";
Have fun!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With