Three.js如何在用户看不到3d空间时停止渲染

three.js how to stop render when the user can't see the 3d space?

本文关键字:空间 3d 看不到 js 用户 Three      更新时间:2023-09-26

我正在制作一个旋转的简单球体渲染。到目前为止,一切都很好,但我想基本上暂停渲染时,用户不再看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;
};

,但这似乎并没有真正停止渲染。

window.cancelAnimationFrame接受window.requestAnimationFrame返回的id,在您的示例中是名为animationFrame的变量。它和setTimeout和clearTimeout是一样的

现在你传递给它一个完整的函数引用,render()函数。在提供的代码中很难跟踪您对全局变量的使用,但您可能只想这样做:

if (animationFrame) {
    stopRendering(animationFrame);
}

因为在你的情况下,你分配由requestAnimationFrame返回的id到变量animationFrame .