I am creating a spinning globe render that I would like to pause when the user is not viewing the dom element containing the renderer. This is important because unnecessary resources are being used when the user cannot see this specific part of the page. Here is what I have implemented so far—
window.addEventListener('scroll', () => {
let scrollPosition = document.body.scrollTop;
//element is almost visible, 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, don't know how to do this
if (animationFrame) {
stopRendering(render);
console.log('render has been halted');
}
}
});
Here is my render()
function—
const render = () => {
animationFrame = requestAnimationFrame( render );
sphere.rotation.y += 0.001;
renderer.render( scene, camera );
isRendering = true;
};
Is there a way to effectively halt the render when the webGL region is out of view?
I attempted something like this in the code above—
var stopRendering = (af) => {
cancelAnimationFrame(af);
isRendering = false;
};
However, this does not actually seem to stop the render process at all.