65 Three.js 使用JSON格式保存和加载整个场景

时间:2022-06-15 04:19:54

前言

本人是用开发指南里面的教程发现在新版本里面你的方法已经无法实现,所以,我们采用保存和加载模型的方法进行实现场景。

实现

案例查看地址:http://www.wjceo.com/blog/threejs/2018-03-18/125.html
首先,将scene场景转化为JSON对象,然后将JSON对象转换成为JSON字符串,就可以存储到本地存储。在案例当中可以通过点击exportScene按钮实现本地存储。

exportScene:function () {
    var sceneJson = JSON.stringify(scene.toJSON());
    localStorage.setItem('scene', sceneJson);
}

然后,点击clearScene按钮,将场景清空。

clearScene:function () {
    scene = new THREE.Scene();
}

最后,再点击importScene按钮,我们就从本地存储中将scene场景数据拿出来,然后将字符串转换成对象,使用THREE.ObjectLoaderparse方法来加载场景对象并重新赋值给scene,场景中即可再次显示出保存的场景。

importScene:function () {
    var json = localStorage.getItem("scene");

    if (json) {
        var loadedGeometry = JSON.parse(json);
        var loader = new THREE.ObjectLoader();

        scene = loader.parse(loadedGeometry);
    }
}

案例代码



 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> html, body { margin: 0; height: 100%; } canvas { display: block; } </style> </head> <body onload="draw();"> </body> <script src="/lib/three.js"></script> <script src="/lib/js/controls/OrbitControls.js"></script> <script src="/lib/js/libs/stats.min.js"></script> <script src="/lib/js/libs/dat.gui.min.js"></script> <script> var renderer; function initRender() { renderer = new THREE.WebGLRenderer({antialias:true}); renderer.setSize(window.innerWidth, window.innerHeight); //告诉渲染器需要阴影效果 renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 默认的是,没有设置的这个清晰 THREE.PCFShadowMap document.body.appendChild(renderer.domElement); } var camera; function initCamera() { camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000); camera.position.set(0, 40, 50); camera.lookAt(new THREE.Vector3(0,0,0)); } var scene; function initScene() { scene = new THREE.Scene(); } //初始化dat.GUI简化试验流程 var gui; function initGui() { //声明一个保存需求修改的相关数据的对象 gui = { exportScene:function () { var sceneJson = JSON.stringify(scene.toJSON()); localStorage.setItem('scene', sceneJson); }, clearScene:function () { scene = new THREE.Scene(); }, importScene:function () { var json = localStorage.getItem("scene"); if (json) { var loadedGeometry = JSON.parse(json); var loader = new THREE.ObjectLoader(); scene = loader.parse(loadedGeometry); } } }; var datGui = new dat.GUI(); //将设置属性添加到gui当中,gui.add(对象,属性,最小值,最大值) datGui.add(gui, "exportScene"); datGui.add(gui, "clearScene"); datGui.add(gui, "importScene"); } var light; function initLight() { scene.add(new THREE.AmbientLight(0x444444)); light = new THREE.PointLight(0xffffff); light.position.set(15,50,10); //告诉平行光需要开启阴影投射 light.castShadow = true; scene.add(light); } var sphere,cube,group; function initModel() { //模型组 group = new THREE.Object3D(); scene.add(group); //球 var sphereGeometry = new THREE.SphereGeometry(5,200,200); var sphereMaterial = new THREE.MeshLambertMaterial({color:0xaaaaaa}); sphere = new THREE.Mesh(sphereGeometry, sphereMaterial); sphere.position.x = -5; sphere.position.y = 5; //告诉球需要投射阴影 sphere.castShadow = true; group.add(sphere); //辅助工具 var helper = new THREE.AxesHelper(50); scene.add(helper); //立方体 var cubeGeometry = new THREE.CubeGeometry(10,10,8); var cubeMaterial = new THREE.MeshLambertMaterial({color:0x00ffff}); cube = new THREE.Mesh(cubeGeometry, cubeMaterial); cube.position.x = 15; cube.position.y = 5; cube.position.z = -5; //告诉立方体需要投射阴影 cube.castShadow = true; group.add(cube); //底部平面 var planeGeometry = new THREE.PlaneGeometry(100,100); var planeMaterial = new THREE.MeshStandardMaterial({color:0xaaaaaa}); var plane = new THREE.Mesh(planeGeometry, planeMaterial); plane.rotation.x = - 0.5 * Math.PI; plane.position.y = -0; //告诉底部平面需要接收阴影 plane.receiveShadow = true; scene.add(plane); } //初始化性能插件 var stats; function initStats() { stats = new Stats(); document.body.appendChild(stats.dom); } //用户交互插件 鼠标左键按住旋转,右键按住平移,滚轮缩放 var controls; function initControls() { controls = new THREE.OrbitControls( camera, renderer.domElement ); // 如果使用animate方法时,将此函数删除 //controls.addEventListener( 'change', render ); // 使动画循环使用时阻尼或自转 意思是否有惯性 controls.enableDamping = true; //动态阻尼系数 就是鼠标拖拽旋转灵敏度 //controls.dampingFactor = 0.25; //是否可以缩放 controls.enableZoom = true; //是否自动旋转 controls.autoRotate = false; //设置相机距离原点的最远距离 controls.minDistance = 100; //设置相机距离原点的最远距离 controls.maxDistance = 200; //是否开启右键拖拽 controls.enablePan = true; } var step = 0.02; //模型旋转的速度 function render() { //判断当前是否自动旋转 if(gui.rotate){ //判断是单个模型自转,还是模型组自转 if(gui.grouping){ group.rotation.y += step; } else{ sphere.rotation.y += step; cube.rotation.y += step; } } renderer.render( scene, camera ); } //窗口变动触发的函数 function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); render(); renderer.setSize( window.innerWidth, window.innerHeight ); } function animate() { //更新控制器 render(); //更新性能插件 stats.update(); controls.update(); requestAnimationFrame(animate); } function draw() { initGui(); initRender(); initScene(); initCamera(); initLight(); initModel(); initControls(); initStats(); animate(); window.onresize = onWindowResize; } </script> </html>