I am currently developing a website that heavily relies on JavaScript and animations. The first section features a fullscreen three.js scene that reacts to mouse movement. While the scene itself functions properly, I have noticed that everything is continuously rendered even when the user is not actively viewing the three.js webgl canvas. This has led to performance issues, especially when other animations are occurring further down the webpage.
To address this problem, I need to find a way to completely pause rendering of the scene when it is not within the viewport, which should significantly improve performance.
Below is the render function being used:
const render = () => {
requestAnimationFrame(render);
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (mouseY * -1 - camera.position.y) * 0.05;
camera.lookAt(scene.position);
const t = Date.now() * 0.001;
const rx = Math.sin(t * 0.6) * 0.5;
const ry = Math.sin(t * 0.3) * 0.5;
const rz = Math.sin(t * 0.2) * 0.5;
group.rotation.x = rx;
group.rotation.y = ry;
group.rotation.z = rz;
textMesh.rotation.x = rx;
textMesh.rotation.y = ry;
textMesh.rotation.z = rx; // :)
renderer.render(scene, camera);
};
render();
Here is my attempt to add functionality for pausing rendering (taken from another source but encountering difficulties in implementation):
var stopRendering = (af) => {
cancelAnimationFrame(af);
isRendering = false;
};
window.addEventListener('scroll', () => {
let scrollPosition = document.body.scrollTop;
if (scrollPosition >= ("#canvas-wrapper")-50) {
if (everythingIsLoaded && !isRendering) {
render();
console.log('render has been started');
} else {
// Wait until everythingIsLoaded becomes true
}
} else {
if (render) {
stopRendering(render);
console.log('render has been halted');
}
}
});
It's worth mentioning that I am utilizing the locomotive scroll library for scroll and viewport visibility detection. This may impact the behavior of basic scrolling events.
The primary objective behind implementing rendering pauses is to significantly enhance overall performance.
Working solution can be found here for reference.