Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register onkeydown event for HTML5 canvas

Tags:

html5-canvas

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
like image 364
Kinematic Avatar asked Mar 26 '13 07:03

Kinematic


1 Answers

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!

like image 64
Niet the Dark Absol Avatar answered Sep 19 '22 07:09

Niet the Dark Absol