How to register onkeydown event for HTML5 canvas

2019-02-18 05:24发布

问题:

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

回答1:

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!



回答2:

If an HTML element is not designed for text input then you cannot set a keydown event for it.

As you have done use

window.addEventListener("keydown", divertDirection, false);

then use the divertDirection function to change the direction of the snake object. If you have more than one snake then use different keys for each snake.