Created
February 9, 2021 20:40
-
-
Save zadvorsky/86b949beab2b3db41476b1ea4f1904cf to your computer and use it in GitHub Desktop.
Store a THREE.js camera position and (Orbit) controls target between page refreshes. Handy if you're working on a scene and refreshing often.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Use the Web Storage API to save camera position and target between page refreshes. | |
* | |
* @param {Object} options | |
* @param {*} options.camera - The camera you want to store the position of. | |
* @param {*} [options.controls] - A controls object with a `.target` property. | |
* @param {String} [options.name="main"] - An optional label. Useful if you want to store multiple cameras. | |
* @param {Boolean} [options.session=true] - Indicates if you want to use local or session storage. | |
* See https://developer.mozilla.org/en-US/docs/Web/API/Storage | |
*/ | |
export default ({ | |
camera, | |
controls, | |
name = 'main', | |
session = true | |
}) => { | |
const store = session ? window.sessionStorage : window.localStorage | |
const positionKey = `three-camera-${name}-position` | |
const targetKey = `three-camera-${name}-target` | |
const positionValue = store.getItem(positionKey) | |
const targetValue = store.getItem(targetKey) | |
if (positionValue) { | |
camera.position.copy(JSON.parse(positionValue)) | |
} | |
if (controls && targetValue) { | |
controls.target.copy(JSON.parse(targetValue)) | |
controls.update() | |
} | |
window.addEventListener('pagehide', () => { | |
store.setItem(positionKey, JSON.stringify(camera.position)) | |
if (controls) { | |
store.setItem(targetKey, JSON.stringify(controls.target)) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment