[webGL学习技术分享]基于three.js构建WebGL实例

Posted 码疯窝编程君

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[webGL学习技术分享]基于three.js构建WebGL实例相关的知识,希望对你有一定的参考价值。

大多程序员在刚开始理解3D(webGL)的知识时,通常对三维空间可能理解的比较困难,你也可能有困难理解不同的光线是如何工作的,或轴甚至如何位于空间。

今天,我会帮你处理这些问题。three.js所拥有一切必要的手段来为这个 - 帮手。在今天的例子中,我已经准备好为你工作的所有现有佣工示范:ArrowHelper,AxisHelper,BoundingBoxHelper,CameraHelper,DirectionalLightHelper,GridHelper,HemisphereLightHelper,PointLightHelper,SpotLightHelper。所有这些将有助于你理解的WebGL的内部工作原理。

html

这部分没有变,跟之前的一样.

<!DOCTYPE html><html lang="en" >
    <head>
        <meta charset="utf-8" />
        <meta name="author" content="Script Tutorials" />
        <title>WebGL With Three.js - Lesson 2 | Script Tutorials</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <link href="css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <script src="js/three.min.js"></script>
        <script src="js/THREEx.WindowResize.js"></script>
        <script src="js/OrbitControls.js"></script>
        <script src="js/stats.min.js"></script>
        <script src="js/script.js"></script>

        <div style="position: absolute; top: 10px; left: 20px; text-align: center;"></div>

        <!-- Only used for Script Tutorial's Demo site. Please ignore and remove. -->
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
        <script src="http://www.script-tutorials.com/assets/ads.js" async></script>
    </body></html>
    
      
      
    

    javascript代码

    首先,让我们来创建一些简单的场景,包括以下内容:摄像头,光线直射,地面和两个领域:

    var dLight, bboxHelper, dlightHelper;// load texturevar texture = THREE.ImageUtils.loadTexture('texture.png');
    texture.repeat.set(10, 10);
    texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
    texture.anisotropy = 16;
    texture.needsUpdate = true;var textureBump = THREE.ImageUtils.loadTexture('bump.png');
    textureBump.repeat.set(10, 10);
    textureBump.wrapS = textureBump.wrapT = THREE.RepeatWrapping;
    textureBump.anisotropy = 16;
    textureBump.needsUpdate = true;var lesson3 = {
        scene: null,
        camera: null,
        renderer: null,
        container: null,
        controls: null,
        clock: null,
        stats: null,
    
        init: function() { // Initialization// create main scene

    this.scene = new THREE.Scene();        var SCREEN_WIDTH = window.innerWidth,

       SCREEN_HEIGHT = window.innerHeight;        
    // prepare camera

    var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 10000;        this.camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);        this.scene.add(this.camera);        this.camera.position.set(-1600, 600, 1200);        this.camera.lookAt(new THREE.Vector3(0,0,0));        
    // prepare renderer

    this.renderer = new THREE.WebGLRenderer({antialias:true, alpha: false});        this.renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);     this.renderer.setClearColor(0xffffff);        this.renderer.shadowMapEnabled = true;        this.renderer.shadowMapSoft = true;        
    // prepare container

    this.container = document.createElement('div');

    document.body.appendChild(this.container);        this.container.appendChild(this.renderer.domElement);   
    // events

    THREEx.WindowResize(this.renderer, this.camera);        
    // prepare controls (OrbitControls)

    this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);        this.controls.target = new THREE.Vector3(0, 0, 0);      
    // prepare clock

    this.clock = new THREE.Clock();        
    // prepare stats

    this.stats = new Stats();        this.stats.domElement.style.position = 'absolute';      this.stats.domElement.style.bottom = '0px';        this.stats.domElement.style.zIndex = 10;        this.container.appendChild( this.stats.domElement );    
    // add directional light

    dLight = new THREE.DirectionalLight(0xffffff); dLight.position.set(0, 400, 0);

    dLight.castShadow = true;        
    // dLight.shadowCameraVisible = true;

    dLight.shadowMapWidth = dLight.shadowMapHeight = 1000;  this.scene.add(dLight);        
    // add simple ground

    var groundGeometry = new THREE.PlaneGeometry(1200, 1200, 1, 1); ground = new THREE.Mesh(groundGeometry, new THREE.MeshLambertMaterial({     color: 0x9669FE})); ground.position.y = -20; ground.rotation.x = - Math.PI / 2;

    ground.receiveShadow = true;        this.scene.add(ground);        
    // create a new group (Object3D)

    var group = new THREE.Object3D();        
    // add two spheres

    var sphere  = this.drawSphere(-100, 150, new THREE.MeshPhongMaterial({ map: texture, bumpMap: textureBump, color: 0x00ff00, specular: 0xff2200, emissive: 0x004000 })); var sphere2 = this.drawSphere( 100, 150, new THREE.MeshPhongMaterial({ map: texture, bumpMap: textureBump, color: 0x00ff00, specular: 0xff2200, shininess: 3 }));       
    // and add them into the group

    group.add(sphere);

    group.add(sphere2);        this.scene.add(group);        
    // add helpers:

    // 1. ArrowHelper

    var directionV3 = new THREE.Vector3(1, 0, 1);        var originV3 = new THREE.Vector3(0, 200, 0);        var arrowHelper = new THREE.ArrowHelper(directionV3, originV3, 100, 0xff0000, 20, 10); // 100 is length, 20 and 10 are head length and width

    this.scene.add(arrowHelper);        
    // 2. AxisHelper

    var axisHelper = new THREE.AxisHelper(800); // 500 is size

    this.scene.add(axisHelper);        
    // 3. BoundingBoxHelper

    bboxHelper = new THREE.BoundingBoxHelper(group, 0x999999);        this.scene.add(bboxHelper);        
    // 4. CameraHelper

    var cameraParObj = new THREE.Object3D(); cameraParObj.position.y = 200;

    cameraParObj.position.z = 700;        this.scene.add(cameraParObj);

    perspectiveCamera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.01, 1500);

    cameraParObj.add(perspectiveCamera);        var cameraHelper = new THREE.CameraHelper(perspectiveCamera);        this.scene.add(cameraHelper);        
    // 5. DirectionalLightHelper

    dlightHelper = new THREE.DirectionalLightHelper(dLight, 50); // 50 is helper sizethis.scene.add(dlightHelper); }, drawSphere: function(x, z, material) {var sphere = new THREE.Mesh(new THREE.SphereGeometry(70, 70, 20), material); sphere.rotation.x = sphere.rotation.z = Math.PI * Math.random(); sphere.position.x = x; sphere.position.y = 100; sphere.position.z = z; sphere.castShadow = sphere.receiveShadow = true;        return sphere;    }

    };
    // Animate the scenefunction animate() {

       requestAnimationFrame(animate);    render();    update();

    }
    // Update controls and statsfunction update() {

       bboxHelper.update();    dlightHelper.update();    lesson3.controls.update(lesson3.clock.getDelta());

       lesson3.stats.update();    
    // smoothly move the dLight

       var timer = Date.now() * 0.000025;    dLight.position.x = Math.sin(timer * 5) * 300;    dLight.position.z = Math.cos(timer * 5) * 300;

    }
    // Render the scenefunction render() {

       if (lesson3.renderer) {        lesson3.renderer.render(lesson3.scene, lesson3.camera);    }

    }
    // Initialize lesson on page loadfunction initializeLesson() {

       lesson3.init();    animate();

    }if (window.addEventListener)

       window.addEventListener('load', initializeLesson, false);else if (window.attachEvent)

       window.attachEvent('onload', initializeLesson);else window.onload = initializeLesson;

      请注意两个球体加入到该组(这是普通的对象的3D对象)。现在,我们可以开始下面的功能实现介绍。

      ArrowHelper

      它利用一个轴对象以可视化的3轴以简单的方式。X轴是红色的。Y轴是绿色的。Z轴是蓝色的。这有助于理解在空间的所有三个轴的方向。要添加这个帮手,使用下面的代码:

      //  AxisHelpervar axisHelper = new THREE.AxisHelper(800);this.scene.add(axisHelper);

        BoundingBoxHelper

        它绘制线条对象的任何对象(Object3D)的外接矩形框,显示此对象的世界轴对齐边框。记住我们结合在单组对象这两个领域?要添加这个帮手,使用下面的代码:

        //3. BoundingBoxHelperbboxHelper = new THREE.BoundingBoxHelper(group, 0x999999);this.scene.add(bboxHelper);

          CameraHelper

          它吸引的特定对象3D对象(它看起来像金字塔)与线几何,这有助于可视化什么指定摄像机包含在它的视锥。要添加这个帮手,使用下面的代码:

          // 4. CameraHelper

          var cameraParObj = new THREE.Object3D();cameraParObj.position.y = 200;cameraParObj.position.z = 700;this.scene.add(cameraParObj);perspectiveCamera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.01, 1500);cameraParObj.add(perspectiveCamera);var cameraHelper = new THREE.CameraHelper(perspectiveCamera);this.scene.add(cameraHelper);

            DirectionalLightHelper

            它绘制一个线对象以显示定向的光的方向。我们将逐步把我们的光源的给你看显然这帮手。要添加这个帮手,使用下面的代码:

            // 5. DirectionalLightHelperdlightHelper = new THREE.DirectionalLightHelper(dLight, 50); // 50 is helper sizthis.scene.add(dlightHelper);

              GridHelper

              要查看佣工的其余部分,我们创建了第二个演示。其次是GridHelper,这个辅助绘制线条的二维网格。要添加这个帮手,使用下面的代码:

              var gridHelper = new THREE.GridHelper(500, 40); // 500 is grid size, 20 is grid stepgridHelper.position = new THREE.Vector3(0, 0, 0);gridHelper.rotation = new THREE.Euler(0, 0, 0);this.scene.add(gridHelper);var gridHelper2 = gridHelper.clone();gridHelper2.rotation = new THREE.Euler(Math.PI / 2, 0, 0);this.scene.add(gridHelper2);var gridHelper3 = gridHelper.clone();gridHelper3.rotation = new THREE.Euler(Math.PI / 2, 0, Math.PI / 2);this.scene.add(gridHelper3);

                HemisphereLightHelper

                其余3个助手是灯,HemisphereLightHelper是HemisphereLight对象。我们不得不关闭我们的定向光,使半球光。要添加这个帮手,使用下面的代码:

                // add hemisphere light

                var hemiLight = new THREE.HemisphereLight(0x0000ff, 0x00ff00, 0.4);hemiLight.color.setHSL(0.6, 1, 0.6);hemiLight.groundColor.setHSL(0.095, 1, 0.75);hemiLight.position.set(-200, 400, -200);this.scene.add(hemiLight);var hlightHelper = new THREE.HemisphereLightHelper(hemiLight, 50, 300)// 50 is sphere size, 300 is arrow lengththis.scene.add(hlightHelper);

                  PointLightHelper

                  类似以前的点光源助手是点光源的对象。要添加这个帮手,使用下面的代码:

                  // add point lightvar pointLight = new THREE.PointLight(0xffff00, 1.0);

                  pointLight.position.set(300,300,300);this.scene.add(pointLight);var pointLightHelper = new THREE.PointLightHelper(pointLight, 50); // 50 is sphere sizethis.scene.add(pointLightHelper);

                    SpotLightHelper

                    最后,我们添加了聚光灯下:聚光灯Helper是聚光灯的对象。要添加这个帮手,使用下面的代码:

                    // add spot light

                    var spotLight = new THREE.SpotLight(0xffffff);spotLight.position.set(-300,400,300);spotLight.castShadow = true;spotLight.shadowCameraFov = 60;this.scene.add(spotLight);var spotLightHelper = new THREE.SpotLightHelper(spotLight, 50); // 50 is sphere sizethis.scene.add(spotLightHelper);

                      结束

                      源码下载请点击”阅读原文“

                      以上是关于[webGL学习技术分享]基于three.js构建WebGL实例的主要内容,如果未能解决你的问题,请参考以下文章

                      three.js学习笔记 之一(ITAEM团队学习分享)

                      cesium 和 Three.js有啥区别,以及二者与WebGL 的关系

                      WebGL/Three.js深度学习课程详解

                      Web3D|基于WebGL的Three.js框架|入门篇

                      WebGL和three.js的关系是啥样的?

                      S170WebGL和Three.js精通课程深度解析一门通2019高清完整资源