Currently, I am using ThreeJS to create a basic 3D scene with OrbitControls. The problem I'm facing is that it causes my entire website to lag, even when the user is not actively looking at the scene. I am in need of a function that can start and stop the rendering based on certain conditions, such as when the user is not viewing the canvas. Although I have a start function that works properly, the stop function does not seem to be functioning correctly, resulting in significant slowdowns after ThreeJS initializes.
Despite my efforts to find a solution, I have come across several potential fixes that do not seem to work with my specific application. It appears that these solutions may be outdated and incompatible with the current version of ThreeJS.
Below is an excerpt from my main.js file:
var scene,
camera,
controls,
render,
requestId = undefined;
function init() {
scene = new THREE.Scene();
var threeJSCanvas = document.getElementById("threeJS");
camera = new THREE.PerspectiveCamera( 75, threeJSCanvas.width / threeJSCanvas.height, 0.1, 1000 );
controls = new THREE.OrbitControls( camera );
// Customize Controls and Camera settings
// Generate Geometry.
}
function render() {
requestId = requestAnimationFrame(render);
renderer.render(scene, camera);
}
function start() {
render();
}
function stop() {
window.cancelAnimationFrame(requestId);
requestId = undefined;
}
In another JavaScript file, within the pageChange function of my multi-page application, there is a conditional statement as follows:
if (page == 5) { // The page containing the canvas
if (!locationsRendered) {
init();
locationsRendered = true;
}
} else { // If the page does not have the canvas
if (locationsRendered) {
stop();
}
}
The variable locationsRendered
is initialized earlier in this secondary JavaScript file within the local scope.
I would greatly appreciate any assistance in resolving this issue, as it is crucial that this simple 3D scene does not cause lag throughout my application once it has been loaded. This situation is simply not practical.