我正在制作一个旋转的简单地球仪渲染。到目前为止一切都很好,但是当用户不再查看渲染器所属的dom元素时,我基本上暂停渲染,因为元素是一个向下的方式在页面上,宝贵的资源被用在他们不必要的地方。这是我到目前为止所拥有的 -
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;
};
但这似乎并没有真正停止渲染。
答案 0 :(得分:1)
window.cancelAnimationFrame
接受window.requestAnimationFrame
返回的ID,在您的情况下,该ID是名为animationFrame
的变量。它与setTimeout和clearTimeout相同。
现在你传递一个完整的函数引用render()
函数。在提供的代码中跟踪全局变量的使用很困难,但您可能只想这样做:
if (animationFrame) {
stopRendering(animationFrame);
}
因为在您的情况下,您将requestAnimationFrame
返回的ID分配给变量animationFrame
。