簡體   English   中英

為什么cancelAnimationFrame不取消requestAnimationFrame?

[英]Why cancelAnimationFrame doesn't cancel the requestAnimationFrame?

我不明白為什么cancelAnimationFrame方法不取消requestAnimationFrame 它仍然控制台記錄消息。 任何人都可以提供解釋嗎?

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="Interaktywny poradnik szybkiego startu dla Brackets.">
    <link rel="stylesheet" href="test.css">

  </head>
  <body>

<div class="box1" style="height:100px;width:100px;background:red">
</div>

</body>

<script>

let container;
container = document.getElementsByClassName('box1')[0];
let increase=0
let animate;
         function increaseHeight(){
                    increase = increase + 2;
                    container.style.height=increase + "px";
          if(increase>200){
            console.log("cancelAnimation");
          cancelAnimationFrame(animate)
          }
      animate = requestAnimationFrame(increaseHeight);
        }
    increaseHeight();
</script>

</html>

我認為你真正想做的是

const container = document.getElementsByClassName('box1')[0];
let increase = 0;
function increaseHeight() {
    if (increase < 200) {
        increase = increase + 2;
        container.style.height = increase + "px";
        requestAnimationFrame(increaseHeight); // continue animation
    } else {
        console.log("stopping animation");
    }
}
increaseHeight();

無需取消。

它不是取消,因為您在取消已經運行的框架后請求新框架。 您需要將新的幀請求放入if(increase<200){塊中。 此外,您實際上不應該取消任何東西。 一個 animation 幀請求只運行一次,然后如果要運行另一個,則必須請求另一個。 所以,當你的 animation 完成后,不要再要求另一個,你會很好的。

暫無
暫無

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

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