zoukankan      html  css  js  c++  java
  • 【记】three.js的一个简单的代码记录

        有时间首次尝试了一下three.js,这真是个非常强大的框架,以下就是本人的第一个three.js的"helloworld"。

        关于how to get start,总结起来就是以下这几步

    1. 引入three.js,创建必要的html结构
    2. 创建渲染器
    3. 创建相机
    4. 创建一个场景
    5. 添加相关的模型
    6. 渲染
        多了不说,直接上代码:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8"/>
    <title>HelloWorld</title>
    <style>
    #view
    {width:1600px; height:800px;}
    </style>
    <script src="three.min.js"></script>
    </head>

    <body onLoad="start();">
    <div id="view"></div>
    <script>
    var view=document.getElementById('view');
    var width=view.clientWidth;//宽度
    var height=view.clientHeight;//高度
    var renderer=new THREE.WebGLRenderer({antialias:true});//生成渲染器,带抗锯齿
    var camera;//相机
    var scene;//场景
    var light;//光源
    var obj;//物体
    function initRenderer(){
        renderer.setSize(width,height);//设置宽高
        view.appendChild(renderer.domElement);//将渲染器加入到html中
        renderer.setClearColorHex(0xffffff,1.0);//设置环境的背景色
    }
    function initCamera(){
        camera=new THREE.PerspectiveCamera(45, width/height,1,5000);
        camera.position.x=100;//相机的位置坐标
        camera.position.y=0;//相机的位置坐标
        camera.position.z=100;//相机的位置坐标
        camera.up.x=0;//相机的上方向,该属性是单位向量。相当于一个照相机可以竖着排,也可以横着排
        camera.up.y=1;
        camera.up.z=0;
        camera.lookAt({x:0,y:0,z:0});//相机的朝向,单位向量
    }
    function initScene(){
        scene=new THREE.Scene();//场景
    }
    function initLight(){
        light=new THREE.DirectionalLight(0x0000f0,1.0,0);//光源
        light.position.set(200,200,200);
        scene.add(light);
    }
    function initObject(){
        obj=new THREE.Mesh(
            new THREE.CubeGeometry(20,20,20),
            new THREE.MeshLambertMaterial({color:0xfffff0})
        );
        scene.add(obj);
        obj.position.set(0,0,0);
    }
    var st=0;
    function start(){
        initRenderer();
        initCamera();
        initScene();
        initLight();
        initObject();
        renderer.clear();
        renderer.render(scene,camera);
        animate();
    }

    function animate(){
        var x=Math.cos(Math.PI*st/180)*100;
        var y=Math.sin(Math.PI*st/180)*100;
        camera.position.x=x;
        camera.position.z=y;
        camera.lookAt({x:x/100,y:0,z:y/100});
        //camera.up.x=x;
        //camera.up.z=y;
        st++;
        renderer.clear();
        renderer.render(scene,camera);
        console.log(x+"|"+y);
        setTimeout(animate,30);
    }
    </script>
    </body>
    </html>

         上述代码我旋转了照相机,实现了一个正方体的旋转。唯一觉得稍微难理解的就是相机的那几个向量所代表的意思。

     

  • 相关阅读:
    taglib
    ThinkPHP魔术方法
    给图片添加文字
    公益筹模板
    清空(数据库+文件夹)
    php——文件下载
    查询上一个tp语句
    安装wampserver 2.5的时候出现丢失MSVCR100.dll的解决办法。
    ThinkPHP3.2.3 安装教程
    java基础——File类的基本用法
  • 原文地址:https://www.cnblogs.com/echoloyuk/p/2795024.html
Copyright © 2011-2022 走看看