在HTML5画布中创建关键事件的最佳方法是什么?

use*_*816 18 javascript keyboard html5 canvas

请建议为HTML5画布创建关键事件的最佳方法.我不喜欢任何图书馆,但如果你认为这是最好的方式,那就去回答吧.提前致谢!

Rhy*_*ono 18

这将返回密钥代码:

<canvas id="myCanvas" width="200" height="100" style="background:green"></canvas>
<script type="text/javascript">
window.addEventListener('keydown',this.check,false);

function check(e) {
    alert(e.keyCode);
}
</script>
Run Code Online (Sandbox Code Playgroud)

如果您想根据键显示不同的事情:

function check(e) {
    var code = e.keyCode;
    //Up arrow pressed
    if (code == 38)
        alert("You pressed the Up arrow key");
    else
        alert("You pressed some other key I don't really care about.");
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您有一长串要使用的密钥,请在交换机案例中执行:

function check(e) {
    var code = e.keyCode;
    switch (code) {
        case 37: alert("Left"); break; //Left key
        case 38: alert("Up"); break; //Up key
        case 39: alert("Right"); break; //Right key
        case 40: alert("Down"); break; //Down key
        default: alert(code); //Everything else
    }
}
Run Code Online (Sandbox Code Playgroud)


Bri*_*can 8

如果要在<canvas>自身(而不是windowdocument)上设置键事件处理,请在<canvas>元素上设置tabindex .请注意,画布需要专注于捕获关键事件.

<script>
    document.getElementById('game').addEventListener('keypress', handleKeyPress);
    function handleKeyPress(e) { ... }
</script>
<canvas id="game" tabindex="1" width="350" height="200">
</canvas>
Run Code Online (Sandbox Code Playgroud)

这是在Processing.js网站上完成的.

如果在单击画布时不希望显示边框,请将其样式设置为outline: none.