65 Three.js save and load the whole scene in JSON format

Preface

I use the tutorial in the development guide to find that your method can no longer be implemented in the new version, so we use the method of saving and loading the model to implement the scenario.

Realization

Case view address:
First, the scene scene is transformed into a JSON object, and then the JSON object is transformed into a JSON string, which can be stored locally. In the case, you can click the export scene button to realize local storage.

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

Then, click the clearScene button to clear the scene.

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

Finally, click the import scene button, we will take the scene scene data out of the local storage, then convert the string into an object, use the parse method of the THREE.ObjectLoader to load the scene object and reassign it to the scene, and the saved scene will be displayed again in the scene.

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

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

        scene = loader.parse(loadedGeometry);
    }
}

Case code



<!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);
        //Tell the renderer you need shadow effects
        renderer.shadowMap.enabled = true;
        renderer.shadowMap.type = THREE.PCFSoftShadowMap; // By default, there is no clear thread.pcfshadowmap set
        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();
    }

    //Initialize dat.GUI to simplify the test process
    var gui;
    function initGui() {
        //Declare an object to save the relevant data of the requirement modification
        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();
        //Add the setting attribute to the GUI, gui.add (object, attribute, min, max)
        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);

        //Tell directional light to turn on shadow casting
        light.castShadow = true;

        scene.add(light);
    }

    var sphere,cube,group;
    function initModel() {

        //Model group
        group = new THREE.Object3D();
        scene.add(group);

        //The Ball
        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;

        //Tell the ball to cast shadows
        sphere.castShadow = true;

        group.add(sphere);

        //Auxiliary tools
        var helper = new THREE.AxesHelper(50);
        scene.add(helper);

        //Cube
        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;

        //Tell the cube to cast shadows
        cube.castShadow = true;

        group.add(cube);

        //Bottom plane
        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;

        //Tell the bottom plane to receive shadows
        plane.receiveShadow = true;

        scene.add(plane);

    }

    //Initialize performance plug-ins
    var stats;
    function initStats() {
        stats = new Stats();
        document.body.appendChild(stats.dom);
    }

    //User interaction plug in left mouse button press and hold rotation, right mouse button press and hold translation, scroll wheel zoom
    var controls;
    function initControls() {

        controls = new THREE.OrbitControls( camera, renderer.domElement );

        // If you use the animate method, delete this function
        //controls.addEventListener( 'change', render );
        // Whether there is inertia in the meaning of damping or rotation when the animation is recycled
        controls.enableDamping = true;
        //Dynamic damping coefficient is the mouse drag rotation sensitivity
        //controls.dampingFactor = 0.25;
        //Can I zoom
        controls.enableZoom = true;
        //Auto rotate or not
        controls.autoRotate = false;
        //Set the maximum distance between the camera and the origin
        controls.minDistance  = 100;
        //Set the maximum distance between the camera and the origin
        controls.maxDistance  = 200;
        //Enable right drag
        controls.enablePan = true;
    }

    var step = 0.02; //Speed of model rotation
    function render() {

        //Determine whether the current rotation is automatic
        if(gui.rotate){
            //Determine whether a single model rotates or a group of models rotates
            if(gui.grouping){
                group.rotation.y += step;
            }
            else{
                sphere.rotation.y += step;
                cube.rotation.y += step;
            }
        }

        renderer.render( scene, camera );
    }

    //Function triggered by window change
    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        render();
        renderer.setSize( window.innerWidth, window.innerHeight );

    }

    function animate() {
        //Update controller
        render();

        //Update performance plug-ins
        stats.update();

        controls.update();

        requestAnimationFrame(animate);
    }

    function draw() {
        initGui();
        initRender();
        initScene();
        initCamera();
        initLight();
        initModel();
        initControls();
        initStats();

        animate();
        window.onresize = onWindowResize;
    }
</script>
</html>

Tags: JSON Attribute

Posted on Fri, 03 Apr 2020 09:56:05 -0700 by exhaler