Skip to content

Instantly share code, notes, and snippets.

@zadvorsky
Created February 9, 2021 20:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zadvorsky/86b949beab2b3db41476b1ea4f1904cf to your computer and use it in GitHub Desktop.
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.
/**
* 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