Created
February 9, 2021 20:07
-
-
Save manthrax/8e9d71ed5efe2f865846d3516d029fc0 to your computer and use it in GitHub Desktop.
Save/Load camera/controls target
This file contains 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