簡體   English   中英

HTML Canvas:按住鍵時控制鍵按下注冊表

[英]HTML Canvas: Controlling keydown registry when key is held down

我正在尋找一種方法來控制在按下鍵的情況下在給定的時間段內注冊了多少鍵按下事件。 我有兩個動畫函數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變量在字符串數組中循環。 當崩潰()觸發時,arrayCount會增加1。 不幸的是,當按下鍵時,它會快速連續觸發折疊功能,並且陣列循環過快。

是否可以限制按鍵事件的時間,以便說一半的按鍵被注冊?

我嘗試將變量heldDown設置為false ,這將允許keyEvent注冊。 keyEvent將調用collapse並啟動heldDownTimer 一旦heldDownTimer過期, heldDown將被重置為false並且循環將重新開始。

設置標志,指​​示折疊和展開動畫的當前狀態。

var doCollapsing指示折疊代碼是否應設置動畫。

var doExpanding指示擴展代碼是否應設置動畫。

在keydown處理程序中,僅當標志指示動畫循環處於空閑狀態時,才設置標志,可以忽略“額外” 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
    }

這將導致折疊+展開執行一次,而不是每次按下鍵都會被觸發。

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM