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

2022-01-13 00:00:00 keyboard canvas javascript html

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

Please suggest the best way to create key events for HTML5 canvas. I don't prefer any library, but if you think that it's the best way then go answer it. Thanks in advance!

推荐答案

这将返回关键代码:

<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>

如果您想演示基于密钥所做的不同事情:

If you would like a demonstration of different things being done based on key:

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.");
}

或者,如果您有一长串要使用的键,请在开关盒中进行:

Or if you have a long list of keys you'll be using, do it in a switch case:

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
    }
}

相关文章