删除 JavaScript 中的按键延迟?

2022-01-17 00:00:00 javascript html5-canvas dom-events

好吧,当您按住键盘上的某个键时,第一次开火后会有 1 秒的延迟.
您可以继续打开记事本并按住一个键(例如x"),您会在第一次火灾后看到有延迟.

Well, when you hold a key on your keyboard, after the first fire there is a 1sec delay.
You can go ahead and open notepad and hold a key (e.x 'x') you'll see after the first fire there is a delay.

但是,我正在尝试使用 JavaScript 在 HTML5 Canvas 中开发游戏,并且 1 秒的延迟非常烦人,此外,它还会停止玩家行走动画..

However, I'm trying to develop a game in HTML5 Canvas with JavaScript, and that 1sec delay is very annoying, Additionally, it stops the player walking animation..

那么我怎样才能删除 JavaScript 中令人讨厌的延迟(没有 jQuery!)?

So how can I delete that annoying delay in JavaScript ( no jQuery! ) ?

我的 keydown 事件在这种模式下工作 -

My keydown event works in this pattern -

document.onkeydown = getKey;
function getKey(e) {
    switch(e.keyCode) {
        case 38: // UP
            Player.PositionY--;
        break;
        case 39: // RIGHT
            Player.PositionX++;
        break;
        case 40: // DOWN
            Player.PositionY++;
        break;
        case 37: // LEFT
            Player.PositionX--;
        break;
    }
}

推荐答案

你可以在 keydown 上启动一个事件并在 keyup

you could start an event on keydown and stop it on keyup

$('#mycanvas').on('keydown', function() { 
   $(document).trigger('start'); 
}); 

$('#mycanvas').on('keyup', function() { 
   $(document).trigger('stop'); 
});

$(document).on('start', startAnimation);
$(document).on('stop', stopAnimation);

function startAnimation(e) { //start something }
function stopAnimation(e) { //stop something }

相关文章