three.js初级教程(一)画线

前几个星期突然接了小程序的任务,所以three.js的教程就晚点发布了。

直接上代码,先码上html和css:

 
重点在js代码上:

        //重构成规范的模式
        var 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(0xFFFFFF, 1.0);
        }

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

        var scene;
        function initScene(){
            scene = new THREE.Scene();

        }

        var light;
        function initLight() {
            light = new THREE.DirectionalLight(0xFF0000, 1.0, 0);
            light.position.set(100, 100, 200);
            scene.add(light);
        }

        var cube;
        function initObject(){
            var geometry = new THREE.Geometry();
            var material = new THREE.LineBasicMaterial({vertexColors:THREE.VertexColors});
            var color1 = new THREE.Color( 0x444444 ), color2 = new THREE.Color( 0xFF0000 );
            // 线的材质可以由2点的颜色决定
            var p1 = new THREE.Vector3( 100, 0, 100 );
            var p2 = new THREE.Vector3( -100, 0, -100 );
            geometry.vertices.push(p1);
            geometry.vertices.push(p2);
            geometry.colors.push( color1, color2 );

            //第一个参数是几何体,第二个参数是材质或者线的属性,第三个参数是一组点的连接方式
            var line = new THREE.Line( geometry, material, THREE.LinePieces );
            scene.add(line);
        }

        function render()
        {
            renderer.clear();
            renderer.render(scene, camera);
            requestAnimationFrame(render);
        }
        function threeStart() {
            initThree();
            initCamera();
            initScene();
            initLight();
            initObject();
            render();
        }
        window.onload =function(){
            threeStart();
        }
    


 renderer,camera和scene是三个重要的组成部分。以上就画出了线。是不是很easy呢!

你可能感兴趣的:(Three.js,javascript,three.js)