加载保存JSON对象
2019-11-12 本文已影响0人
Codifier
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Load And Save JSON Object</title>
<script src="../../three-part/threejs/three.js"></script>
<script src="../../three-part/utils/stats.min.js"></script>
<script src="../../three-part/utils/dat.gui.min.js"></script>
<script src="../controls/TrackballControls.js"></script>
<script src="../util/util.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="container"></div>
<script type="text/javascript">
init();
function init() {
// show FPS
let stats = initStats();
// resize
window.addEventListener('resize', onResize, false);
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.x = 0;
camera.position.y = 40;
camera.position.z = 50;
camera.lookAt(scene.position);
let renderer = new THREE.WebGLRenderer();
renderer.setClearColor(new THREE.Color(0x000000));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.getElementById("container").appendChild(renderer.domElement);
// init trackball control
let trackballControls = initTrackballControls(camera, renderer);
let clock = new THREE.Clock();
let knot = createMesh(new THREE.TorusKnotGeometry(10, 1, 64, 8, 2, 3));
scene.add(knot);
// attributes which can be modified in GUI
const controls = {
"save" : function () {
let result = knot.toJSON();
localStorage.setItem("json", JSON.stringify(result));
},
"load" : function(){
scene.remove(loadedMesh);
let json = localStorage.getItem("json");
if (json) {
let loadedGeometry = JSON.parse(json);
let loader = new THREE.ObjectLoader();
loadedMesh = loader.parse(loadedGeometry);
loadedMesh.position.x -= 40;
scene.add(loadedMesh);
}
}
};
// init GUI
initGUI();
let loadedMesh;
renderScene();
function initGUI(){
let gui = new dat.GUI();
gui.add(controls, 'save');
gui.add(controls, 'load');
}
function createMesh(geom) {
let meshMaterial = new THREE.MeshNormalMaterial();
meshMaterial.side = THREE.DoubleSide;
let mesh = new THREE.Mesh(geom, meshMaterial);
mesh.position.set(0, 0, 0);
return mesh;
}
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function renderScene(){
trackballControls.update(clock.getDelta());
stats.update();
requestAnimationFrame(renderScene);
renderer.render(scene, camera);
}
}
</script>
</body>
</html>
运行结果: