我有一个Web应用程序,用户可以在其中添加对象到场景,移动它,更改旋转等。但是,我有一个下拉列表,它决定了整个页面上各个参数所遵循的单位系统。下拉,更改时应该通过页面刷新。这会导致整个场景重置。有没有办法保存场景,然后在三个js中重新加载到以前的状态?
答案 0 :(得分:4)
你想要实现的一个很好的例子是three.js editor本身。你可以在github找到它的来源。
它将编辑器的状态(即配置,camera
和scene
个对象)存储到local storage
和indexedDB
中是什么意思(你只能忍受它)一个也)然后当页面被初始化时,它检查是否在state
中设置了场景indexedDB
,它从那里加载它。
您可能需要对代码本身进行一些阅读,但我将在此解释主要逻辑。
当有这段代码时,您可以在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
文件。
再次在index.html
中,您可以找到以下代码并更新IndexedDB
中的模型,可以在事件或超时时触发此行为,甚至可以通过调用此段代码手动触发editor.storage.set( editor.toJSON() );
1}}。
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 );
};
希望您可以利用此示例来实现目标。