如何解决JavaScript键下的延迟 [英] How to fix delay in javascript keydown

查看:143
本文介绍了如何解决JavaScript键下的延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JavaScript移动延迟和多个键击

m新和学习HTML5画布与javascript。我创建了一个事件来左右移动对象,我的问题是延迟每当你按住键或切换到另一个键。我知道我的代码下面缺少,请帮助我。提前感谢。

I'm new and learning HTML5 canvas together with javascript. I've created an event to move an object left and right, and my problem is the delay whenever you hold the key or switch to another key. I know there's missing on my code below please help me. Thank you in advance.

c.addEventListener('keydown',this.check,true);
  function check(el) {
    var code = el.keyCode || el.which;
    if (code == 37 || code == 65){
    x -=1;
    }

    if (code == 39 || code == 68){
    x += 1;
    }

  el.preventDefault();
}


推荐答案

对于keydown事件,我建议你使用keydown和keyup事件来维护一个列表,哪些键当前下来。然后实现一个游戏循环,它检查每个x毫秒的键失效,并相应地更新显示。

Rather than trying to react directly to the keydown event, I'd suggest you use the keydown and keyup events to maintain a list of which keys are presently down. Then implement a "game loop" that checks every x milliseconds which keys are down and update the display accordingly.

var keyState = {};    
window.addEventListener('keydown',function(e){
    keyState[e.keyCode || e.which] = true;
},true);    
window.addEventListener('keyup',function(e){
    keyState[e.keyCode || e.which] = false;
},true);

x = 100;

function gameLoop() {
    if (keyState[37] || keyState[65]){
        x -= 1;
    }    
    if (keyState[39] || keyState[68]){
        x += 1;
    }

    // redraw/reposition your object here
    // also redraw/animate any objects not controlled by the user

    setTimeout(gameLoop, 10);
}    
gameLoop();

你会注意到,这可以让你一次处理多个键,例如,左和上箭头在一起,并且当按下键时随后的键按下事件之间的延迟的问题消失,因为你真正关心的是键发生是否发生。

You'll notice that this lets you handle multiple keys at once, e.g., if the user presses the left and up arrows together, and the problem of delay between subsequent keydown events when a key is held down goes away since all you really care about is whether a keyup has occurred.

我意识到你可能没有实现一个游戏,但这个游戏循环的概念应该为你工作,如这个非常简单的演示: http ://jsfiddle.net/nnnnnn/gedk6/

I realise you may not be implementing a game, but this "game loop" concept should work for you as shown in this very simple demo: http://jsfiddle.net/nnnnnn/gedk6/

这篇关于如何解决JavaScript键下的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆