一段时间后取消 requestAnimationFrame 循环

我想在超时后取消动画。这是我的代码


function animate(){

        id = requestAnimationFrame(animate);

        console.log(id);

        c.clearRect(0,0, window.innerWidth, window.innerHeight);

        for(let i = 0; i < circleArray.length; i++){

            circleArray[i].scatter();

        }

        setTimeout(function(){

            id = requestAnimationFrame(animate);

            cancelAnimationFrame(id);

            update();

        },5000)

    }

    

    function update(){

        requestAnimationFrame(update);

        c.clearRect(0,0, window.innerWidth, window.innerHeight);

        for(let i = 0; i < circleArray.length; i++){

            circleArray[i].update();

        }

    }

在这里,我想停止动画功能的递归并启动更新功能。但是动画不会停止,并且更新功能会在给定时间后同时运行。


蝴蝶刀刀
浏览 494回答 1
1回答

慕桂英546537

只需使用一个变量来引用当前渲染函数并在计时器事件上更改该变量。例子var currentFrameRender = animate;&nbsp; // set current renderrequestAnimationFrame(currentFrameRender); // request first framesetTimeout(() => currentFrameRender = update ,5000); // switch render in 5ssetTimeout(() => currentFrameRender = undefined ,10000); // stop animation in 10sfunction animate(){&nbsp; &nbsp; c.clearRect(0, 0, c.canvas.width, c.canvas.height);&nbsp; &nbsp; for(let i = 0; i < circles.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; circleArray[i].scatter();&nbsp; &nbsp; }&nbsp; &nbsp; // request frame only if currentFrameRender is defined&nbsp; &nbsp; currentFrameRender && requestAnimationFrame(currentFrameRender);}function update(){&nbsp; &nbsp; c.clearRect(0, 0, c.canvas.width, c.canvas.height);&nbsp; &nbsp; for(let i = 0; i < circles.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; circleArray[i].update();&nbsp; &nbsp; }&nbsp; &nbsp; // request frame only if currentFrameRender is defined&nbsp; &nbsp; currentFrameRender && requestAnimationFrame(currentFrameRender);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript