Build your first three.js example

Build your first three.js example

Before formally learning three, you can do a few demos first, so that you can have a preliminary understanding of three, so that you can have an outline in the follow-up study, and you can also know where to find the corresponding points during development. Where to go for problems.

The picture below is the effect of this demo

insert image description here

Coordinate System

The coordinate system supports the right-hand rule. In the figure, the red is the x-axis, the green is the y-axis, and the blue is the z-axis.

code analysis

        <div id="container"></div>

        //容器
        const container = document.getElementById('container')
        let sWidth = document.getElementById('container').clientWidth
        let scale = window.innerWidth / window.innerHeight
        console.log(sWidth, scale)
        //清空容器
        if(container.childNodes.length > 0){
    
    
            let node = document.getElementsByTagName('canvas')[0]
            container.removeChild(node)
        }
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera( 45, scale, 0.1, 1000 );
        var renderer = new THREE.WebGLRenderer();
        renderer.setClearColor(new THREE.Color('black'))
        renderer.setSize(sWidth, sWidth / scale)
        // 坐标轴大小
        var axes = new THREE.AxesHelper(20)
        scene.add(axes)
        // 创建地面
        var planeGeometry = new THREE.PlaneGeometry(60, 20);
        var planeMaterial = new THREE.MeshBasicMaterial({
    
    
            color: 0xAAAAAA
        });
        var plane = new THREE.Mesh(planeGeometry, planeMaterial);
        // r旋转地面
        plane.rotation.x = -0.5 * Math.PI;
        plane.position.set(15, 0, 0);

        // 添加地面到场景中
        scene.add(plane);
        // 添加方块
        var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
        var cubeMaterial = new THREE.MeshBasicMaterial({
    
    
            color: 0xFF0000,
            wireframe: true
        });
        var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

        // 设置方块位置
        cube.position.set(-4, 3, 0);

        // 添加方块到场景中
        scene.add(cube);
        // 创建球体
        var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
        var sphereMaterial = new THREE.MeshBasicMaterial({
    
    
            color: 0x7777FF,
            wireframe: true
        });
        var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);

        // 设置球体位置
        sphere.position.set(20, 4, 2);

        // a添加球体到场景中
        scene.add(sphere);

        // 放置相机位置
        camera.position.set(-30, 40, 30);
        camera.lookAt(scene.position);
        // 添加canvas节点
        container.appendChild(renderer.domElement);
        // 渲染
        renderer.render(scene, camera)

Guess you like

Origin blog.csdn.net/qq_35517283/article/details/129874851