如何修复javascript keydown中的延迟 [英] How to fix delay in javascript keydown

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

问题描述

可能的重复:
JavaScript 移动延迟和多次击键

我是新手,正在学习 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();

您会注意到,这让您可以同时处理多个键,例如,如果用户同时按下向左和向上箭头,那么当一个键被按下时后续 keydown 事件之间的延迟问题就会消失,因为您所有的真正关心的是是否发生了keyup.

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 keydown中的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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