您试图实现的一个美好例子是three.js editor本身。您可以在github上找到它的源代码。
它是什么,它存储在(即配置,camera和scene对象)编辑器的状态进入local storage和indexedDB,然后(你可以只用一个也住)时,页面初始化它会检查是否场景的state被设置在indexedDB那里,它从那里加载它。
您可能需要阅读代码本身,但我会在此解释主要逻辑。
1.装载从本地存储场景时的页面加载
可以发现,在index.html当有这段代码
editor.storage.init(function() {
editor.storage.get(function (state) {
if (state !== undefined) {
editor.fromJSON(state);
}
var selected = editor.config.getKey('selected');
if (selected !== undefined) {
editor.selectByUuid(selected);
}
});
所以这个检查,如果有数据处于fromJSON函数/js/Editor.js,它基本上将camera和scene等设置为存储在indexedDB中的任何值。看到的确切代码是
fromJSON: function (json) {
var loader = new THREE.ObjectLoader();
// backwards
if (json.scene === undefined) {
var scene = loader.parse(json);
this.setScene(scene);
return;
}
// TODO: Clean this up somehow
var camera = loader.parse(json.camera);
this.camera.position.copy(camera.position);
this.camera.rotation.copy(camera.rotation);
this.camera.aspect = camera.aspect;
this.camera.near = camera.near;
this.camera.far = camera.far;
this.setScene(loader.parse(json.scene));
this.scripts = json.scripts;
}
要检查其怎么装从本地存储/ IndexedDB的正是你可以检查位于该JS文件夹本身Config.js和Storage.js文件。
第二存储数据到IndexedDB的周期性
再在index.html你可以找到下面的代码并更新IndexedDB模型这种行为上的事件或超时被触发,甚至通过手动调用这段代码editor.storage.set(editor.toJSON());。
var saveState = function (scene) {
if (editor.config.getKey('autosave') === false) {
return;
}
clearTimeout(timeout);
timeout = setTimeout(function() {
editor.signals.savingStarted.dispatch();
timeout = setTimeout(function() {
editor.storage.set(editor.toJSON());
editor.signals.savingFinished.dispatch();
}, 100);
}, 1000);
};
希望你可以利用这个例子来实现你的目标。