three.js - (入門四)

很久沒更新three.js 了,前三章瞭解了部分基礎知識。這一章咱們來搞點事情,作點有意思的東西。html

效果以下圖:jquery

由於截圖是靜止的,實際效果是地球在自轉。服務器

廢話很少說,上代碼:app

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>erath - three.js</title>
    <script src="js/three.js"></script>
    <script src="js/jquery.min.js"></script>
</head>
<style>
    * {
        padding: 0px;
        margin: 0px;
    }
        html,body,.main {
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
</style>
<body>
    <div class="main"></div>
</body>
</html>
<script>
    function Three(className) {
        this.width = $(className).width();
        this.height = $(className).height();
        this.renderer =  new THREE.WebGLRenderer({
            antialias : true   //開啓鋸齒,默認是false
        });
        this.renderer.setSize(this.width, this.height); // 給渲染區域設置寬高
        this.renderer.setClearColor("white"); // 設置背景色
        $(className).append(this.renderer.domElement); 
    }
    Three.prototype = {
        init:function() {
            this.scence = new THREE.Scene();  // 建立舞臺
            
            // 設置視角及參數
            this.camera = new THREE.PerspectiveCamera(45, this.width / this.height, 1, 10000);
            this.camera.position.set(0,0,10);
            this.camera.lookAt(new THREE.Vector3(0, 0, 0));

        // 設置燈光及參數
            this.light = new THREE.AmbientLight(0xDDDDDD);
            this.light.position.set(100, 100, 200);
            this.scence.add(this.light);

            // 建立角色
            var circle =  new THREE.SphereGeometry(755,50,50);
            var texture = new THREE.TextureLoader();
            
            var material = new THREE.MeshBasicMaterial();
            // 給circle添加背景圖片
            material.map = texture.load("images/earth_atmos_4096.jpg",function(){
                three.renderer.render(three.scence, three.camera);
            });
            three.mesh = new THREE.Mesh(circle,material);
            three.mesh.position.set(0,0,-5000);
            three.scence.add(three.mesh);
        },
        animate:function() {
            requestAnimationFrame(three.animate);
            three.mesh.rotation.y += 0.01;
            three.renderer.render(three.scence, three.camera);
        },
        start:function() {
            this.init();
            this.animate();
        }
    }
    var three = new Three(".main");
    three.start();
</script>

這裏我把地球圖片上傳上來,否則沒有圖片也沒法加載。dom

最後提醒你們一點,當有圖片加載到three.js 時,須要在服務器端運行。否則也會報錯。this

今天的three.js 就講到這裏了,下次再會。spa

相關文章
相關標籤/搜索