HTML Canvas:按住键时控制keydown注册表

时间:2014-09-10 03:12:29

标签: javascript html animation canvas

我正在寻找一种方法来控制在按住某个键的特定时间段内注册了多少次keydown事件。我有两个动画功能collapse()expand(),当按下向下键时,它会折叠并展开一个框。我已经操纵它,以便第二个动画在第一个动画之后开始。但是,我在第一个动画中设置了一个定时器hovering(t),该动画会在每次按键时重置,这样第二个动画就不会开始,直到释放按键并且定时器到期为止。

    function collapse(){

        if(h > 1 && arrayCount < myArray.length){
          reqAnimFrame(collapse);
          h -= 10;
          clear();
          draw();
        } else {
          arrayCount += 1;
          h = 0;
          clearHoverTimer();
          hovering(250); 
        }
    }

    function expand(){

        if(h < 100){
          reqAnimFrame(expand);
          h += 10;
          clear();
          draw();
        } else {
          h = 100;
          clear();
          draw();
        }
    }

这里我的问题是:第一个动画函数还通过arrayCount变量遍历一个字符串数组。当collapse()触发时,arrayCount递增1。不幸的是,当按下按键时,它会快速连续地触发折叠功能,并且阵列通过太快的方式循环。

是否可以限制按键事件的时间,以便说一半的按键被注册?

我尝试将变量heldDown设置为false,这将允许keyEvent注册。 keyEvent将调用collapse并启动heldDownTimerheldDownTimer到期后,heldDown将重置为false,周期将重新开始。

1 个答案:

答案 0 :(得分:0)

设置标记,指示折叠的当前状态&amp;扩大动画。

var doCollapsing表示折叠代码是否应设置动画。

var doExpanding表示扩展代码是否应该设置动画。

在你的keydown处理程序中,你可以忽略&#39;额外的&#39; keydown只在它们指示动画循环空闲时设置标志。

    // listen for keydown and doCollapsing only if the animation is currently idle
    if(!doCollapsing && !doExpanding){
        doCollapsing=true;  // start collapsing
        doExpanding=false;  // don't expand until a keyup fires
    }

这将导致崩溃+扩展执行一次,而不是每次keydown都会触发。

// variables indicating the state of the animation
var doCollapsing=false;
var doExpanding=false;


// listen for keydown events
document.addEventListener("keydown",handleKeydown,false);


// listen for keyup events
document.addEventListener("keyup",handleKeyup,false);


// start the animation loop
requestAnimationFrame(animate);


// handle keydown events
function handleKeydown(e){

    // listen for keydown
    // doCollapsing only if the animation is idle
    if(!doCollapsing && !doExpanding){
        doCollapsing=true;
        doExpanding=false;
    }

}


// handle keyup events
function handleKeyup(e){
    doExpanding=true;
}


// the animation loop
function animate(time){
    requestAnimationFrame(animate);

    if(doCollapsing){
        // Do collapsing until done
        // When done: doCollapsing=false;
    }else if(doExpanding && hoveringTimerHasExpired){
        // Do expanding until done
        // When done: doExpanding=false;
    }

}