首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么cancelAnimationFrame不取消requestAnimationFrame?

为什么cancelAnimationFrame不取消requestAnimationFrame?
EN

Stack Overflow用户
提问于 2019-11-17 05:29:29
回答 2查看 76关注 0票数 0

我不明白为什么cancelAnimationFrame方法不取消requestAnimationFrame。它仍然在控制台上记录消息。有谁能解释一下吗?

代码语言:javascript
复制
<!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>
EN

回答 2

Stack Overflow用户

发布于 2019-11-17 05:33:52

我觉得你真正想做的是

代码语言:javascript
复制
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();

不需要取消。

票数 0
EN

Stack Overflow用户

发布于 2019-11-17 05:34:32

它不是取消,因为在取消已经运行的帧之后,您正在请求新的帧。您需要将新的帧请求放入if(increase<200){块中。另外,你实际上不应该取消任何事情。一个动画帧请求只运行一次,如果你想运行另一个,你必须请求另一个。所以,当你的动画制作完成后,只要不要求另一个动画,你就会做得很好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58895395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档