Three.js的魔法城堡(一)

Published: 2015-10-28

Tags: Three.js

本文总阅读量
  1. Demo
  2. 阴影
  3. 运动
  4. 调速

想学习Three.js的同学可下载这本书来看《Learning Three.js - Dirksen, Jos》 本学习笔记摘自书中的代码仅作学习笔记之用

1. Demo

01

如上的图形就是个挺不错的例子,代码如下

<!DOCTYPE html>

<html>

<head>
    <title>Example 01.02 - First Scene</title>
    <script type="text/javascript" src="http://cdn.staticfile.org/three.js/r69/three.min.js"></script>
    <style>
        body {
            /* set margin to 0 and overflow to hidden, to go fullscreen */
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>

<!-- 用来保存输出结果 -->
<div id="WebGL-output">
</div>

<script type="text/javascript">

    // 当页面加载完成时运行初始化函数, 完成绘制
    function init() {

        // 首先创建一个场景,各种元素都将添加到场景
        var scene = new THREE.Scene();

        // 创建一个我们的视角
        var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);

        // 创建一个渲染器
        var renderer = new THREE.WebGLRenderer();
        renderer.setClearColorHex();
        renderer.setClearColor(new THREE.Color(0xEEEEEE));
        renderer.setSize(window.innerWidth, window.innerHeight);

        // 添加坐标轴到场景
        var axes = new THREE.AxisHelper(20);
        scene.add(axes);

        // 创建一个平面层
        var planeGeometry = new THREE.PlaneGeometry(60, 20);
        var planeMaterial = new THREE.MeshBasicMaterial({color: 0xcccccc});
        var plane = new THREE.Mesh(planeGeometry, planeMaterial);

        // 旋转并设置平面层位置
        plane.rotation.x = -0.5 * Math.PI;
        plane.position.x = 15;
        plane.position.y = 0;
        plane.position.z = 0;

        // 将平面层加入到场景
        scene.add(plane);

        // 创建一个正方体
        var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
        var cubeMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, wireframe: true});
        var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

        // 设置这个正方体的位置
        cube.position.x = -4;
        cube.position.y = 3;
        cube.position.z = 0;

        // 添加方体到场景中
        scene.add(cube);

        // 创建一个球体
        var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
        var sphereMaterial = new THREE.MeshBasicMaterial({color: 0x7777ff, wireframe: true});
        var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);

        // 设置球体的位置
        sphere.position.x = 20;
        sphere.position.y = 4;
        sphere.position.z = 4;

        // 添加球体到场景中
        scene.add(sphere);

        // 设置视角的位置
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        // 添加图形到div层
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        // 渲染场景
        renderer.render(scene, camera);
    }
    window.onload = init;

</script>
</body>
</html>

Demo还是很简单明了的,基本看过注释就能理解了

2. 阴影

下面,对Demo添加阴影,使用Three.js来很容易实现,主要有三点需要改变

  • 修改材质
  • 设置对象为可投影的
  • 添加聚光灯

1,修改材质

如上的例子中我们通过MeshBasicMaterial方法使用线框(wireframe)来表示正方体和球

修改为MeshLambertMaterialMeshPhongMaterial方法可改变其材质

2,设置对象为可投影的

通过设置receiveShadow来告诉渲染器开启阴影功能

renderer.setClearColor(new THREE.Color(0xEEEEEE));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;

然后设置receiveShadow使得背景平面接受投影

var planeGeometry = new THREE.PlaneGeometry(60, 20);
var planeMaterial = new THREE.MeshLambertMaterial({color: 0xffffff});
var plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.receiveShadow = true;

在创建对象的时候设置castShadow使对象成为可投影的

var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xff0000});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.castShadow = true;

3,添加聚光灯

在这之前,修改材质,修改物体为可以产生阴影的,但是没有光,那么也不会有阴影

var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(-40, 60, -10);
spotLight.castShadow = true;
scene.add(spotLight);

添加聚光灯,阴影就会产生了

02

完整代码如下

<!DOCTYPE html>

<html>

<head>
    <title>learning three.js</title>
    <script type="text/javascript" src="http://cdn.staticfile.org/three.js/r69/three.min.js"></script>
    <style>
        body {
            /* set margin to 0 and overflow to hidden, to go fullscreen */
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>

<!-- 用来保存输出结果 -->
<div id="WebGL-output">
</div>

<script type="text/javascript">

    // 当页面加载完成时运行初始化函数, 完成绘制
    function init() {

        // 首先创建一个场景,各种元素都将添加到场景
        var scene = new THREE.Scene();

        // 创建一个我们的视角
        var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);

        // 创建一个渲染器
        var renderer = new THREE.WebGLRenderer();
        renderer.setClearColorHex();
        renderer.setClearColor(new THREE.Color(0xEEEEEE));
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMapEnabled = true;

        // 添加坐标轴到场景
        var axes = new THREE.AxisHelper(20);
        scene.add(axes);

        // 创建一个平面层
        var planeGeometry = new THREE.PlaneGeometry(60, 20);
        var planeMaterial = new THREE.MeshBasicMaterial({color: 0xcccccc});
        var plane = new THREE.Mesh(planeGeometry, planeMaterial);
        plane.receiveShadow = true;

        // 旋转并设置平面层位置
        plane.rotation.x = -0.5 * Math.PI;
        plane.position.x = 15;
        plane.position.y = 0;
        plane.position.z = 0;

        // 将平面层加入到场景
        scene.add(plane);

        // 创建一个正方体
        var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xff0000});
        var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.castShadow = true;

        // 设置这个正方体的位置
        cube.position.x = -4;
        cube.position.y = 3;
        cube.position.z = 0;

        // 添加方体到场景中
        scene.add(cube);

        // 创建一个球体
        var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
        var sphereMaterial = new THREE.MeshLambertMaterial({color: 0x7777ff});
        var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        sphere.castShadow = true;

        // 设置球体的位置
        sphere.position.x = 20;
        sphere.position.y = 4;
        sphere.position.z = 4;

        // 添加球体到场景中
        scene.add(sphere);

        // 设置视角的位置
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        // 添加聚光灯
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        scene.add(spotLight);

        // 添加图形到div层
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        // 渲染场景
        renderer.render(scene, camera);
    }
    window.onload = init;

</script>
</body>
</html>

3. 运动

在HTML5及新的JS API出来之前,如果想要实现运动,需要interval来轮询,这种方式会导致高CPU计算量,并且性能很低

现在我们使用requestAnimationFrame()可以指定我们的函数去执行,浏览器会很好的去执行他,相对于2的代码,这里有两个改动的地方

  • 添加指示器
  • 使物体运动

1,添加指示器

引入stats.js

<script type="text/javascript" src="http://cdn.staticfile.org/stats.js/r11/Stats.min.js"></script>

在body中添加div层来放置stats组件

<div id="Stats-output">
</div>

定义initStats()函数

function initStats() {

  var stats = new Stats();

  stats.setMode(0); // 0: fps, 1: ms

  // Align top-left
  stats.domElement.style.position = 'absolute';
  stats.domElement.style.left = '0px';
  stats.domElement.style.top = '0px';

  document.getElementById("Stats-output").appendChild(stats.domElement);

  return stats;
}

然后在init函数中添加如下代码调用initStats()函数

$(function () {
    var stats = initStats();
     ...
})

2,使物体运动

之前使用的函数直接是

renderer.render(scene, camera);

现在把它包裹在函数renderScene()中,在函数中,对物体的坐标进行变换

function renderScene() {
     stats.update();
     // rotate the cube around its axes
     cube.rotation.x += 0.02;
     cube.rotation.y += 0.02;
     cube.rotation.z += 0.02;

     // bounce the sphere up and down
     step += 0.04;
     sphere.position.x = 20 + ( 10 * (Math.cos(step)));
     sphere.position.y = 2 + ( 10 * Math.abs(Math.sin(step)));

     // render using requestAnimationFrame
     requestAnimationFrame(renderScene);
     renderer.render(scene, camera);
}

函数中每次都调用requestAnimationFrame函数进行更新,并且在最开始处对stats进行状态更新

完整的代码如下

<!DOCTYPE html>

<html>

<head>
    <title>learning three.js</title>
    <meta charset="utf-8">
    <!-- <script type="text/javascript" src="../libs/three.js"></script> -->
    <script type="text/javascript" src="http://cdn.staticfile.org/three.js/r69/three.min.js"></script>
    <script type="text/javascript" src="http://cdn.staticfile.org/stats.js/r11/Stats.min.js"></script>
    <style>
        body {
            /* set margin to 0 and overflow to hidden, to go fullscreen */
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>

<!-- 用来保存输出结果 -->
<div id="Stats-output">
</div>

<div id="WebGL-output">
</div>

<script type="text/javascript">

    // 当页面加载完成时运行初始化函数, 完成绘制
    function init() {

        var stats = initStats();

        // 首先创建一个场景,各种元素都将添加到场景
        var scene = new THREE.Scene();

        // 创建一个我们的视角
        var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);

        // 创建一个渲染器
        var renderer = new THREE.WebGLRenderer();
        renderer.setClearColorHex();
        renderer.setClearColor(new THREE.Color(0xEEEEEE));
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMapEnabled = true;

        // 添加坐标轴到场景
        var axes = new THREE.AxisHelper(20);
        scene.add(axes);

        // 创建一个平面层
        var planeGeometry = new THREE.PlaneGeometry(60, 20);
        var planeMaterial = new THREE.MeshBasicMaterial({color: 0xcccccc});
        var plane = new THREE.Mesh(planeGeometry, planeMaterial);
        plane.receiveShadow = true;

        // 旋转并设置平面层位置
        plane.rotation.x = -0.5 * Math.PI;
        plane.position.x = 15;
        plane.position.y = 0;
        plane.position.z = 0;

        // 将平面层加入到场景
        scene.add(plane);

        // 创建一个正方体
        var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xff0000});
        var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.castShadow = true;

        // 设置这个正方体的位置
        cube.position.x = -4;
        cube.position.y = 3;
        cube.position.z = 0;

        // 添加方体到场景中
        scene.add(cube);

        // 创建一个球体
        var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
        var sphereMaterial = new THREE.MeshLambertMaterial({color: 0x7777ff});
        var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        sphere.castShadow = true;

        // 设置球体的位置
        sphere.position.x = 20;
        sphere.position.y = 4;
        sphere.position.z = 4;

        // 添加球体到场景中
        scene.add(sphere);

        // 设置视角的位置
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        // 添加聚光灯
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        scene.add(spotLight);

        // 添加图形到div层
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        // 渲染场景
        var step = 0;
        renderScene();

        function renderScene() {

          stats.update();

          // 对正方体进行坐标变换
          cube.rotation.x += 0.02;
          cube.rotation.y += 0.02;
          cube.rotation.z += 0.02;

          // 对球进行坐标变换
          step += 0.04;
          sphere.position.x = 20 + (10 * (Math.cos(step)));
          sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));

          // 使用requestAnimationFrame进行更新
          requestAnimationFrame(renderScene);
          renderer.render(scene, camera);
        }

        // 初始化状态器
        function initStats() {

          var stats = new Stats();

          stats.setMode(0); // 0: fps, 1: ms

          stats.domElement.style.position = 'absolute';
          stats.domElement.style.left = '0px';
          stats.domElement.style.top = '0px';

          document.getElementById('Stats-output').appendChild(stats.domElement);

          return stats;
        }
    }
    window.onload = init;

</script>
</body>
</html>

动起来的效果如下

03

4. 调速

一些谷歌员工做个个库,可以简单方便的调整参数,名为dat.GUI

接下来添加这个库,实现可以点击调整球体的弹跳速度和正方体的旋转速度

<script type="text/javascript" src="http://cdn.staticfile.org/dat-gui/0.5/dat.gui.min.js"></script>

创建一个对象来保存速度信息,并且给了初始值

var controls = new function() {
    this.rotationSpeed = 0.02;
    this.bouncingSpeed = 0.03;
}

之后,将这个对象传给dat.GUI对象

var gui = new dat.GUI();
gui.add(controls, 'rotationSpeed', 0, 0.5);
gui.add(controls, 'bouncingSpeed', 0, 0.5);

速度的调整区间都为[0, 0.5]

之后在坐标变更的时候添加这个变量

cube.rotation.x += controls.rotationSpeed;
cube.rotation.y += controls.rotationSpeed;
cube.rotation.z += controls.rotationSpeed;

step += controls.bouncingSpeed;
sphere.position.x = 20 + ( 10 * (Math.cos(step)));
sphere.position.y = 2 + ( 10 * Math.abs(Math.sin(step)));

还是很容易使用的,看一下最终的效果及代码

04

<!DOCTYPE html>

<html>

<head>
    <title>learning three.js</title>
    <meta charset="utf-8">
    <!-- <script type="text/javascript" src="../libs/three.js"></script> -->
    <script type="text/javascript" src="http://cdn.staticfile.org/three.js/r69/three.min.js"></script>
    <script type="text/javascript" src="http://cdn.staticfile.org/stats.js/r11/Stats.min.js"></script>
    <script type="text/javascript" src="http://cdn.staticfile.org/dat-gui/0.5/dat.gui.min.js"></script>
    <style>
        body {
            /* set margin to 0 and overflow to hidden, to go fullscreen */
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>

<!-- 用来保存输出结果 -->
<div id="Stats-output">
</div>

<div id="WebGL-output">
</div>

<script type="text/javascript">

    // 当页面加载完成时运行初始化函数, 完成绘制
    function init() {

        var stats = initStats();

        // 首先创建一个场景,各种元素都将添加到场景
        var scene = new THREE.Scene();

        // 创建一个我们的视角
        var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);

        // 创建一个渲染器
        var renderer = new THREE.WebGLRenderer();
        renderer.setClearColorHex();
        renderer.setClearColor(new THREE.Color(0xEEEEEE));
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMapEnabled = true;

        // 添加坐标轴到场景
        var axes = new THREE.AxisHelper(20);
        scene.add(axes);

        // 创建一个平面层
        var planeGeometry = new THREE.PlaneGeometry(60, 20);
        var planeMaterial = new THREE.MeshBasicMaterial({color: 0xcccccc});
        var plane = new THREE.Mesh(planeGeometry, planeMaterial);
        plane.receiveShadow = true;

        // 旋转并设置平面层位置
        plane.rotation.x = -0.5 * Math.PI;
        plane.position.x = 15;
        plane.position.y = 0;
        plane.position.z = 0;

        // 将平面层加入到场景
        scene.add(plane);

        // 创建一个正方体
        var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xff0000});
        var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.castShadow = true;

        // 设置这个正方体的位置
        cube.position.x = -4;
        cube.position.y = 3;
        cube.position.z = 0;

        // 添加方体到场景中
        scene.add(cube);

        // 创建一个球体
        var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
        var sphereMaterial = new THREE.MeshLambertMaterial({color: 0x7777ff});
        var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        sphere.castShadow = true;

        // 设置球体的位置
        sphere.position.x = 20;
        sphere.position.y = 4;
        sphere.position.z = 4;

        // 添加球体到场景中
        scene.add(sphere);

        // 设置视角的位置
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        // 添加聚光灯
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        scene.add(spotLight);

        // 添加图形到div层
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        // 渲染场景
        var step = 0;

        // 定义一个运动速度的对象
        var controls = new function() {
          this.rotationSpeed = 0.02;
          this.bouncingSpeed = 0.03;
        }

        // 引入dat.GUI进行交互
        var gui = new dat.GUI();
        gui.add(controls, 'rotationSpeed', 0, 0.5);
        gui.add(controls, 'bouncingSpeed', 0, 0.5);

        renderScene();

        function renderScene() {

          stats.update();

          // 对正方体进行坐标变换
          cube.rotation.x += controls.rotationSpeed;
          cube.rotation.y += controls.rotationSpeed;
          cube.rotation.z += controls.rotationSpeed;

          // 对球进行坐标变换
          step += controls.bouncingSpeed;
          sphere.position.x = 20 + (10 * (Math.cos(step)));
          sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));

          // 使用requestAnimationFrame进行更新
          requestAnimationFrame(renderScene);
          renderer.render(scene, camera);
        }

        // 初始化状态器
        function initStats() {

          var stats = new Stats();

          stats.setMode(0); // 0: fps, 1: ms

          stats.domElement.style.position = 'absolute';
          stats.domElement.style.left = '0px';
          stats.domElement.style.top = '0px';

          document.getElementById('Stats-output').appendChild(stats.domElement);

          return stats;
        }
    }
    window.onload = init;

</script>
</body>
</html>