天天看點

WebGL three.js學習筆記 紋理貼圖模拟太陽系運轉

紋理貼圖的應用以及實作一個太陽系的自轉公轉

點選檢視demo示範

demo位址:https://nsytsqdtn.github.io/demo/solar/solar

three.js中的紋理

紋理貼圖是通過将圖像應用到對象的一個或多個面,來為3D對象添加細節的一種方法。

可以使用TextureLoader類的load方法來加載紋理

function loadImgTexture(){
    var loader = new THREE.TextureLoader();
    loader.load("metal-rust.jpg",function(texture){
        var geometry = new THREE.BoxGeometry(10,10,10);
        var material = new THREE.MeshBasicMaterial({color:0x739783,map:texture});
        mesh = new THREE.Mesh(geometry,material);
        scene.add(mesh);
    })
}
           

實作效果如下:

WebGL three.js學習筆記 紋理貼圖模拟太陽系運轉

八大行星的貼圖資源網上到處都可以找到,這裡給一個還不錯的位址:

https://tieba.baidu.com/p/4876471245?red_tag=3235237836

完整太陽系代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Three.js</title>
    <script src="../../Import/three.js"></script>
    <script src="../../Import/stats.js"></script>
    <script src="../../Import/Setting.js"></script>
    <script src="../../Import/OrbitControls.js"></script>
    <style type="text/css">
        div#canvas-frame {
            border: none;
            cursor: pointer;
            width: 100%;
            height: 850px;
            background-color: #333333;
        }
    </style>
</head>
<body onload="threeStart()">
<script>
    let renderer;
    function initThree() {
        width = document.getElementById('canvas-frame').clientWidth;
        height = document.getElementById('canvas-frame').clientHeight;
        renderer = new THREE.WebGLRenderer({
            antialias : true
        });
        renderer.setSize(width,height);
        document.getElementById("canvas-frame").appendChild(renderer.domElement);
        renderer.setClearColor(0x333333, 1.0);

    }
    let camera;
    function initCamera() {
        camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000);
        camera.position.x = 0;
        camera.position.y = 500;
        camera.position.z = 2000;
        camera.up.x = 0;
        camera.up.y = 1;
        camera.up.z = 0;
        camera.lookAt(0,0,0);
    }

    let scene;
    function initScene() {
        scene = new  THREE.Scene();
        let bgTexture = new THREE.TextureLoader().load("../../Image/universe.jpg");//背景貼圖
        scene.background = bgTexture;//把場景的背景設定為一張圖檔
    }
    let light;
    function initLight() {
        light = new THREE.PointLight(0xffffff,1);//點光源,模拟太陽
        light.position.set(0,0,0);
        scene.add(light);
        light = new THREE.AmbientLight(0xffffff,0.3);//環境光
        scene.add(light);
    }
    let sun;
    let earth;
    let tuxing;
    let shuixing;
    let jinxing;
    let huoxing;
    let muxing;
    let tianwangxing;
    let haiwangxing;
    
    function initObject() {
        let geometry = new THREE.SphereGeometry(15, 50, 50);
        let texture = THREE.ImageUtils.loadTexture("../../Image/shuixing.jpg");//定義一個貼圖,并從本地檔案中加載
        let material = new THREE.MeshBasicMaterial({map:texture});//把上面定義的texture設定為星球的紋理材質
        shuixing = new THREE.Mesh(geometry,material);
        shuixing.position.set(0,0,150);//3
        scene.add(shuixing);

        geometry = new THREE.SphereGeometry(25, 50, 50);
        texture = THREE.ImageUtils.loadTexture("../../Image/jinxing.jpg");
        material = new THREE.MeshBasicMaterial({map:texture});
        jinxing = new THREE.Mesh(geometry,material);
        jinxing.position.set(0,0,200);//4
        scene.add(jinxing);

        geometry = new THREE.SphereGeometry(30, 50, 50);
        texture = THREE.ImageUtils.loadTexture("../../Image/earth.jpg");
        material = new THREE.MeshBasicMaterial({map:texture});
        earth = new THREE.Mesh(geometry,material);
        earth.position.set(0,0,300);//6
        scene.add(earth);

        geometry = new THREE.SphereGeometry(20, 50, 50);
        texture = THREE.ImageUtils.loadTexture("../../Image/huoxing.jpg");
        material = new THREE.MeshBasicMaterial({map:texture});
        huoxing = new THREE.Mesh(geometry,material);
        huoxing.position.set(0,0,400);//8
        scene.add(huoxing);

        geometry = new THREE.SphereGeometry(65, 50, 50);
        texture = THREE.ImageUtils.loadTexture("../../Image/muxing.jpg");
        material = new THREE.MeshBasicMaterial({map:texture});
        muxing = new THREE.Mesh(geometry,material);
        muxing.position.set(0,0,600);//500 12
        scene.add(muxing);
        geometry = new THREE.TorusGeometry(80,6,20,20);
        texture = THREE.ImageUtils.loadTexture("../../Image/muxinghuan.jpg");
        material = new THREE.MeshBasicMaterial({map:texture});
        let muxinghuan = new THREE.Mesh(geometry,material);
        muxinghuan.rotation.x = 1.4;//木星環
        muxing.add(muxinghuan);

        geometry = new THREE.SphereGeometry(55, 50, 50);
        texture = THREE.ImageUtils.loadTexture("../../Image/tuxing.jpg");
        material = new THREE.MeshBasicMaterial({map:texture});
        tuxing = new THREE.Mesh(geometry,material);
        tuxing.position.set(0,0,800);//16
        scene.add(tuxing);
        geometry = new THREE.TorusGeometry(65,8,20,20);
        texture = THREE.ImageUtils.loadTexture("../../Image/tuxinghuan.jpg");
        material = new THREE.MeshBasicMaterial({map:texture});
        let tuxinghuan = new THREE.Mesh(geometry,material);
        tuxinghuan.rotation.x = 1.4;
        tuxing.add(tuxinghuan);

        geometry = new THREE.SphereGeometry(45, 50, 50);
        texture = THREE.ImageUtils.loadTexture("../../Image/tianwangxing.jpg");
        material = new THREE.MeshBasicMaterial({map:texture});
        tianwangxing = new THREE.Mesh(geometry,material);
        tianwangxing.position.set(0,0,950);//19
        scene.add(tianwangxing);

        geometry = new THREE.SphereGeometry(40, 50, 50);
        texture = THREE.ImageUtils.loadTexture("../../Image/haiwangxing.jpg");
        material = new THREE.MeshBasicMaterial({map:texture});
        haiwangxing = new THREE.Mesh(geometry,material);
        haiwangxing.position.set(0,0,1100);//22
        scene.add(haiwangxing);

        geometry = new THREE.SphereGeometry(120, 50, 50);
        texture = THREE.ImageUtils.loadTexture("../../Image/sun.jpg");
        material = new THREE.MeshBasicMaterial({map:texture,
            emissive: 0xffffff,side: THREE.DoubleSide,});
        sun = new THREE.Mesh(geometry,material);
        sun.position.set(0,0,0);
        scene.add(sun);

        //在太陽外面設定一層透明的罩,看上去更像太陽
        let canvas = document.createElement( 'canvas' );
        canvas.width = 256;
        canvas.height = 256;
        let context = canvas.getContext( '2d' );
        let gradient = context.createRadialGradient( canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2 );//建立一個圓形漸變對象
        gradient.addColorStop( 0.1, 'rgba(255,60,0,0.01)' );//内圈的顔色
        gradient.addColorStop( 1, 'rgba(255,125,0,0.5)' );//最外面的顔色
        context.fillStyle = gradient;
        context.fillRect( 0, 0, canvas.width, canvas.height );//将一個畫布使用圓形漸變對象進行填充
        let shadowTexture = new THREE.CanvasTexture( canvas );//把剛剛畫好的畫布拿來作為畫布貼圖
        let shadowMaterial = new THREE.MeshBasicMaterial( { map: shadowTexture,transparent:true } );//用此貼圖來當材質
        let shadowGeo = new THREE.SphereGeometry( 130,50,50);
        let shadowMesh;
        shadowMesh = new THREE.Mesh( shadowGeo, shadowMaterial );
        shadowMesh.position.y = 0;
        shadowMesh.position.x = 0;
        sun.add( shadowMesh );

        //畫線,把太陽系每個星球運作軌迹畫出來
        for(let j=3;j<=22;j++) {
            if (j==3||j==4||j==6||j==8||j==12||j==16||j==19||j==22){
                let radius = 50 * j;
                let lineGeometry2 = new THREE.Geometry();
                for (let i = 0; i <= 2 * Math.PI; i += Math.PI / 30) {
                    lineGeometry2.vertices.push(new THREE.Vector3(radius * Math.cos(i), 0, radius * Math.sin(i), 0))
                }
                let material2 = new THREE.LineBasicMaterial({color: 0x8f6cab})
                let cycleMesh = new THREE.Line(lineGeometry2, material2);
                cycleMesh.position.set(0, 0, 0);
                scene.add(cycleMesh);
            }
            }
    }
    //每個星球的自轉函數
    function zizhuan() {
        sun.rotation.y = sun.rotation.y+0.008>=2*Math.PI?0:sun.rotation.y+0.008;
        shuixing.rotation.y = shuixing.rotation.y+0.005>=2*Math.PI?0:shuixing.rotation.y+0.005;
        jinxing.rotation.y = jinxing.rotation.y+0.003>=0?2*Math.PI:jinxing.rotation.y+0.003;
        earth.rotation.y = earth.rotation.y+0.012>=2*Math.PI?0:earth.rotation.y+0.012;
        huoxing.rotation.y = huoxing.rotation.y+0.01>=2*Math.PI?0:huoxing.rotation.y+0.01;
        tuxing.rotation.y = tuxing.rotation.y+0.04>=2*Math.PI?0:tuxing.rotation.y+0.06;
        muxing.rotation.y = muxing.rotation.y+0.03>=2*Math.PI?0:muxing.rotation.y+0.08;
        tianwangxing.rotation.z = tianwangxing.rotation.z+0.015>=2*Math.PI?0:tianwangxing.rotation.z+0.015;
        haiwangxing.rotation.y = haiwangxing.rotation.y+0.02>=2*Math.PI?0:haiwangxing.rotation.y+0.02;
    }

    let shuixingAngle = 0;
    let jinxingAngle = 0;
    let earthAngle = 0;
    let huoxingAngle = 0;
    let tuxingAngle = 0;
    let muxingAngle = 0;
    let tianwangxingAngle = 0;
    let haiwangxingAngle = 0;
    //每個星球的公轉函數
    function gongzhuan() {
        shuixingAngle = shuixingAngle+0.03>=2*Math.PI?0:shuixingAngle +0.03;
        shuixing.position.set(150*Math.sin(shuixingAngle)
            ,0,150*Math.cos(shuixingAngle));

        jinxingAngle = jinxingAngle-0.02>=0?2*Math.PI:jinxingAngle -0.02;
        jinxing.position.set(200*Math.sin(jinxingAngle)
            ,0,200*Math.cos(jinxingAngle));

        earthAngle = earthAngle+0.015>=2*Math.PI?0:earthAngle +0.015;
        earth.position.set(300*Math.sin(earthAngle)
            ,0,300*Math.cos(earthAngle));

        huoxingAngle = huoxingAngle+0.01>=2*Math.PI?0:huoxingAngle +0.01;
        huoxing.position.set(400*Math.sin(huoxingAngle)
            ,0,400*Math.cos(huoxingAngle));

        muxingAngle = muxingAngle+0.006>=2*Math.PI?0:muxingAngle +0.006;
        muxing.position.set(600*Math.sin(muxingAngle)
            ,0,600*Math.cos(muxingAngle));

        tuxingAngle = tuxingAngle+0.004>=2*Math.PI?0:tuxingAngle +0.004;
        tuxing.position.set(800*Math.sin(tuxingAngle)
            ,0,800*Math.cos(tuxingAngle));

        tianwangxingAngle = tianwangxingAngle+0.003>=2*Math.PI?0:tianwangxingAngle +0.003;
        tianwangxing.position.set(950*Math.sin(tianwangxingAngle)
            ,0,950*Math.cos(tianwangxingAngle));

        haiwangxingAngle = haiwangxingAngle+0.002>=2*Math.PI?0:haiwangxingAngle +0.002;
        haiwangxing.position.set(1100*Math.sin(haiwangxingAngle)
            ,0,1100*Math.cos(haiwangxingAngle));
    }
    function initSetting() {
        loadAutoScreen(camera,renderer);
        loadFullScreen();
        loadStats();
    }
    let controller;
    function threeStart() {
        initThree();
        initCamera();
        initScene();
        initLight();
        initObject();
        initSetting();
        controller = new THREE.OrbitControls(camera,renderer.domElement);
        controller.target = new THREE.Vector3(0,0,0);
        controller.autoRotate = true;
        animation();
    }
    function animation() {
        zizhuan();
        gongzhuan();
        renderer.clear();
        renderer.render(scene,camera);
        requestAnimationFrame(animation);
        stats.update();
    }

</script>
<div id="canvas-frame"></div>
</body>
</html>
           

注意從本地讀取圖檔或者其他檔案時,浏覽器一般是不允許的,是以會出現加載不了紋理或者背景圖檔的情況,隻能在Chrome浏覽器的屬性–目标的最後,加上 --allow-file-access-from-files(前面有一個空格),就可以從這個打開的快捷方式中去讀取到本地檔案,如果是Edge浏覽器似乎就直接可以。也可以使用npm或者tomcat搭建一個本地伺服器,然後把圖檔放進去就可以直接讀取了。