我正在制作一个可以旋转的简单地球仪渲染。到目前为止一切都很好,但是当用户不再查看渲染器作为其子级的 dom 元素时,我基本上希望暂停渲染,因为该元素位于页面和有值(value)的资源被用在了不必要的地方。这是我到目前为止所得到的——
window.addEventListener('scroll', () => {
let scrollPosition = document.body.scrollTop;
//element is almost about to be visible, time to start rendering
if (scrollPosition >= topOfElement - 200) {
if (everythingIsLoaded && !isRendering) {
render();
console.log('render has been started');
} else {
//wait until everythingIsLoaded is true
}
//element is not visible, stop rendering
} else {
//need to stop rendering here!
//this doesn't work, dunno how to do this
if (animationFrame) {
stopRendering(render);
console.log('render has been halted');
}
}
});
我的 render()
函数看起来像这样 -
const render = () => {
animationFrame = requestAnimationFrame( render );
sphere.rotation.y += 0.001;
renderer.render( scene, camera );
isRendering = true;
};
当用户不再能够看到 webGL 渲染区域时,是否有办法停止渲染?
我尝试做这样的事情(正如你在上面的代码中看到的) -
var stopRendering = (af) => {
cancelAnimationFrame(af);
isRendering = false;
};
但这似乎并没有真正停止渲染。
最佳答案
window.cancelAnimationFrame
接受window.requestAnimationFrame
返回的id ,在您的例子中是名为 animationFrame
的变量。它与setTimeout和clearTimeout相同。
现在您正在向其传递整个函数引用,即 render()
函数。很难在提供的代码中跟踪您对全局变量的使用,但您可能只想这样做:
if (animationFrame) {
stopRendering(animationFrame);
}
因为在您的情况下,您将 requestAnimationFrame
返回的 id 分配给变量 animationFrame
。
关于javascript - Three.js 当用户看不到 3d 空间时如何停止渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671606/