将JavaScript添加到requestAnimationFrame函数中

问题描述 投票:0回答:1

该问题可以参考Three.JS框架,但我认为这是一个通用的JS问题。

animate();

function animate() {

    {doSomething}
    requestAnimationFrame( animate );

}

所以函数animate()运行每一帧并执行某些操作。

问题是如何在运行中将{doAnotherSomething}添加到animate()

function anEventHappened(){

     //adding some methods to animate

}
javascript add requestanimationframe on-the-fly
1个回答
1
投票

有几种方法可以做到这一点。但是您将不得不以某种方式预见此动画功能中的某些内容,该功能可以检测到还需要执行更多操作。这个“东西”可能是一个数组,其中包含要执行的功能。最初,该数组为空,但是在某些情况下,您可以向该列表添加一个函数(或从列表中删除一个函数)。

这是一个实际示例:

let container = document.querySelector("pre");
let todoList = []; // <--- list of functions to execute also as extras
animate();

function animate() {
    todoList.forEach(f => f()); // execute whatever is in the todo-list
    moveText(container);
    requestAnimationFrame(animate);
}

document.querySelector("button").onclick = function anEventHappened() {
    let newContainer = document.createElement("pre");
    newContainer.textContent = Math.random();
    document.body.appendChild(newContainer);
    todoList.push(() => moveText(newContainer)); // add something extra
}

// Helper function to perform some HTML-text manipulation
function moveText(what) {
    what.textContent = what.textContent.includes("<") ? what.textContent.slice(1)
        : what.textContent.length < 60 ? " " + what.textContent
        : what.textContent.replace(/ (\S)/, "<$1");
}
<button>Do extra</button>
<pre>phrase</pre>
© www.soinside.com 2019 - 2024. All rights reserved.