2015-05-11 36 views
0

我有一個Web應用程序,用戶可以在該應用程序中添加對象到場景中,移動它,改變旋轉等。但是,我有一個下拉菜單,它決定了整個頁面上的各個參數要遵循的單位制。下拉式更改應通過頁面刷新。這導致整個場景被重置。有什麼方法可以保存場景,然後用三個j將它重新加載到之前的狀態?THREE.js如何在刷新之前保存場景並在頁面刷新完成後加載它?

回答

4

您試圖實現的一個美好例子是three.js editor本身。您可以在github上找到它的源代碼。

它是什麼,它存儲在(即配置,camerascene對象)編輯器的狀態進入local storageindexedDB,然後(你可以只用一個也住)時,頁面初始化它會檢查是否場景的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,它基本上將camerascene等設置爲存儲在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.jsStorage.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); 
}; 

希望你可以利用這個例子來實現你的目標。

相關問題