14/04/2025

ThreeJs reloading model with code updates : keep memory of camera and control position

Ever experienced repetitive fine tuning of threeJS scene ? and camera controls revert back to original position, and you end up wasting time finding right position to check the modifications visually ? the localStorage / sessionStorage javascript objects allow you to store this information and restore it at reload time. All you need is to setup a beforeunload listener that updates storage with current status of cameraPosition, Rotation, and controlTargets. Notice we use our WaveScene threejs object

window.addEventListener('beforeunload', () => {
    localStorage.setItem('cameraPosition', JSON.stringify( window.waveScene.camera.position.toArray()));
    localStorage.setItem('cameraRotation', JSON.stringify( window.waveScene.camera.rotation.toArray()));
    localStorage.setItem('controlsTarget', JSON.stringify( window.waveScene.controls.target.toArray()));
    sessionStorage.setItem('cameraPosition', JSON.stringify( window.waveScene.camera.position.toArray()));
    sessionStorage.setItem('cameraRotation', JSON.stringify( window.waveScene.camera.rotation.toArray()));
    sessionStorage.setItem('controlsTarget', JSON.stringify( window.waveScene.controls.target.toArray()));
});

You can then restore them at page load time. I noticed that sessionStorage works better in the context of vite enabled Hot Machine Reload, or may be I had two hot reloading windows overlapping each other ? try both anyway and let me know what happens. Source : THREEJS DISCUSSION FORUM (localstorage) and GEMINI ANSWER (including url based storage, very interesting for sharing exact position)

// Restore camera and controls state on load
const storedCameraPosition = sessionStorage.getItem('cameraPosition');
const storedCameraRotation = sessionStorage.getItem('cameraRotation');
const storedControlsTarget = sessionStorage.getItem('controlsTarget');
if (storedCameraPosition && storedCameraRotation && storedControlsTarget) {
this.camera.position.fromArray(JSON.parse(storedCameraPosition));
this.camera.rotation.fromArray(JSON.parse(storedCameraRotation));
this.controls.target.fromArray(JSON.parse(storedControlsTarget));
this.controls.update(); // Important to update controls after setting target
}

Leave a Comment

Your email address will not be published. Required fields are marked *

To top