是時候開始咱們致力於WebGL的新系列文章。這是咱們的第一節課,咱們主要作些的基本功能:建立一個場景,相機,渲染器,控制器(OrbitControls)。咱們也將建立簡單的定向光,加上一些對象(不一樣的幾何形狀)的陰影。爲了使事情更快,咱們決定採起一個最流行的WebGL框架——three.js
。爲何使用three.js? 事實上,它是開源的JavaScript框架,它也是增加最迅速的和討論很熱烈的引擎 。在這裏,已經準備了不少會用到的東西,從基本的點和向量,到作準備工做的場景、着色器,甚至立體效果。css
Live Demohtml
咱們能夠省略這一步,可是,一般,咱們在每一節課都會作。這是咱們這節課的HTML結構:web
<!DOCTYPE html> <html lang="en" > <head> <meta charset="utf-8" /> <meta name="author" content="Script Tutorials" /> <title>WebGL With Three.js - Lesson 1 | 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="http://cdnjs.cloudflare.com/ajax/libs/three.js/r69/three.min.js"></script> <script src="http://www.script-tutorials.com/demos/382/js/three.min.js"></script> <script src="http://www.script-tutorials.com/demos/382/js/OrbitControls.js"></script> <script src="http://www.script-tutorials.com/demos/382/js/stats.min.js"></script> <script src="js/script.js"></script> // 咱們待會要寫的內容 </body> </html>
在這段代碼中,咱們引入了全部今天要用到的庫。ajax
我但願你已經見過咱們的demo和想象組成它的基本元素,咱們將一步一步解釋每一個部分的建立。segmentfault
咱們的場景看起來像這樣:瀏覽器
var lesson1 = { scene: null, camera: null, renderer: null, container: null, controls: null, clock: null, stats: null, init: function() { // 初始化 } }; // 使場景動畫化 function animate() { requestAnimationFrame(animate); render(); update(); } // 更新控制器狀態 function update() { lesson1.controls.update(lesson1.clock.getDelta()); lesson1.stats.update(); } // 渲染場景 function render() { if (lesson1.renderer) { lesson1.renderer.render(lesson1.scene, lesson1.camera); } } // 在頁面加載時初始化 lesson 對象 function initializeLesson() { lesson1.init(); animate(); } if (window.addEventListener) window.addEventListener('load', initializeLesson, false); else if (window.attachEvent) window.attachEvent('onload', initializeLesson); else window.onload = initializeLesson;
這是用 three.js 建應用的經常使用結構。幾乎全部的東西都將在init
方法裏建立。app
它們是咱們場景的主要元素,接下來的代碼將建立一個空場景,包含一個前景相機和可用的陰影映射渲染:框架
// 建立主要場景 this.scene = new THREE.Scene(); var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight; // 準備相機 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(-1000, 1000, 0); this.camera.lookAt(new THREE.Vector3(0,0,0)); // 準備渲染 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; // 準備容器 this.container = document.createElement('div'); document.body.appendChild(this.container); this.container.appendChild(this.renderer.domElement); // 事件 THREEx.WindowResize(this.renderer, this.camera);
咱們將相機把相機放在45度角,設爲全屏幕大小,WebGLRenderer設爲白色,再把咱們的場景添加到HTML文檔中,並且在瀏覽器窗口大小變化時,用THREEx.WindowResize 來控制渲染和相機的變化。less
爲了可以在某種程度上控制相機的 —— three.js 給咱們提供了現成的控件。其中之一是 OrbitControls,它能在場景中繞其軸線旋轉。一個小插件stats.min.js
將有助於咱們看到場景的統計(FPS)。dom
// 準備控制器 (OrbitControls) this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement); this.controls.target = new THREE.Vector3(0, 0, 0); // 準備計時器 this.clock = new THREE.Clock(); // 準備統計 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 );
所以,咱們準備好了四個元素。
光是一個場景中的重要元素,在咱們的第一個教程,咱們將建立最簡單的定向光線,由於咱們要添加基本的陰影:
// 添加定向光線 var dLight = new THREE.DirectionalLight(0xffffff); dLight.position.set(1, 1000, 1); dLight.castShadow = true; dLight.shadowCameraVisible = true; dLight.shadowDarkness = 0.2; dLight.shadowMapWidth = dLight.shadowMapHeight = 1000; this.scene.add(dLight); // 添加粒子光線 particleLight = new THREE.Mesh( new THREE.SphereGeometry(10, 10, 10), new THREE.MeshBasicMaterial({ color: 0x44ff44 })); particleLight.position = dLight.position; this.scene.add(particleLight); // 添加簡單的場地 var groundGeometry = new THREE.PlaneGeometry(1000, 1000, 1, 1); ground = new THREE.Mesh(groundGeometry, new THREE.MeshLambertMaterial({ color: this.getRandColor() })); ground.position.y = 0; ground.rotation.x = - Math.PI / 2; ground.receiveShadow = true; this.scene.add(ground);
當咱們建立燈光時,用了兩個參數 castShadow 和 shadowCameraVisible。這將使咱們可以直觀地看到光在哪裏,理解構造的過程(和邊界)的陰影。
你也可能會注意到,在添加光後,咱們增長了一個球形物體——爲你準備的,以便直觀地知道咱們的定向光源在什麼位置。咱們用一個平面做爲地面去接收陰影——咱們設置的receiveShadow
參數爲true
。
咱們將在場景中添加額外的對象。我用一個方法來生成不一樣顏色的部件。這個方法將從顏色列表中隨機返回一個預約義的顏色。
var colors = [ 0xFF62B0, 0x9A03FE, 0x62D0FF, 0x48FB0D, 0xDFA800, 0xC27E3A, 0x990099, 0x9669FE, 0x23819C, 0x01F33E, 0xB6BA18, 0xFF800D, 0xB96F6F, 0x4A9586 ]; getRandColor: function() { return colors[Math.floor(Math.random() * colors.length)]; }
幾何對象是用必要的數據(點、頂點、面等)來描述三維模型。咱們將建立平面的圓、立方體和圓柱體。Extrude Geometry是用來製做從路徑凸出的形狀。咱們要作個凸出的三角形:
// 添加圓形 var circle = new THREE.Mesh(new THREE.CircleGeometry(70, 50), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); circle.rotation.x = - Math.PI / 2; circle.rotation.y = - Math.PI / 3; circle.rotation.z = Math.PI / 3; circle.position.x = -300; circle.position.y = 150; circle.position.z = -300; circle.castShadow = circle.receiveShadow = true; this.scene.add(circle); // 添加方塊 var cube = new THREE.Mesh(new THREE.CubeGeometry(100, 100, 100), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); cube.rotation.x = cube.rotation.z = Math.PI * 0.1; cube.position.x = -300; cube.position.y = 150; cube.position.z = -100; cube.castShadow = cube.receiveShadow = true; this.scene.add(cube); // 添加圓柱 var cube = new THREE.Mesh(new THREE.CylinderGeometry(60, 80, 90, 32), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); cube.rotation.x = cube.rotation.z = Math.PI * 0.1; cube.position.x = -300; cube.position.y = 150; cube.position.z = 100; cube.castShadow = cube.receiveShadow = true; this.scene.add(cube); // 添加不規則的物體 var extrudeSettings = { amount: 10, steps: 10, bevelSegments: 10, bevelSize: 10, bevelThickness: 10 }; var triangleShape = new THREE.Shape(); triangleShape.moveTo( 0, -50 ); triangleShape.lineTo( -50, 50 ); triangleShape.lineTo( 50, 50 ); triangleShape.lineTo( 0, -50 ); var extrude = new THREE.Mesh(new THREE.ExtrudeGeometry(triangleShape, extrudeSettings), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); extrude.rotation.y = Math.PI / 2; extrude.position.x = -300; extrude.position.y = 150; extrude.position.z = 300; extrude.castShadow = extrude.receiveShadow = true; this.scene.add(extrude);
幾何體建好後,咱們能夠建立一個在這個幾何的基礎上的網格。
接下來咱們將建立四個元素:二十面體、八面體、環,和用shapegeometry對象自定義的路徑(形狀):
// 二十面體
var icosahedron = new THREE.Mesh(new THREE.IcosahedronGeometry(70), new THREE.MeshLambertMaterial({ color: this.getRandColor() }));
icosahedron.position.x = -100;
icosahedron.position.y = 150;
icosahedron.position.z = -300;
icosahedron.castShadow = icosahedron.receiveShadow = true;
this.scene.add(icosahedron);
// 八面體 var octahedron = new THREE.Mesh(new THREE.OctahedronGeometry(70), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); octahedron.position.x = -100; octahedron.position.y = 150; octahedron.position.z = -100; octahedron.castShadow = octahedron.receiveShadow = true; this.scene.add(octahedron); // 環 var ring = new THREE.Mesh(new THREE.RingGeometry(30, 70, 32), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); ring.rotation.y = -Math.PI / 2; ring.position.x = -100; ring.position.y = 150; ring.position.z = 100; ring.castShadow = ring.receiveShadow = true; this.scene.add(ring); // 幾何結構 var shapeG = new THREE.Mesh(new THREE.ShapeGeometry(triangleShape), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); shapeG.rotation.y = -Math.PI / 2; shapeG.position.x = -100; shapeG.position.y = 150; shapeG.position.z = 300; shapeG.castShadow = shapeG.receiveShadow = true; this.scene.add(shapeG);
最後,咱們建立一個球體、四面體、圓環、圓環管:
// 球體 var sphere = new THREE.Mesh(new THREE.SphereGeometry(70, 32, 32), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); sphere.rotation.y = -Math.PI / 2; sphere.position.x = 100; sphere.position.y = 150; sphere.position.z = -300; sphere.castShadow = sphere.receiveShadow = true; this.scene.add(sphere); // 四面體 var tetrahedron = new THREE.Mesh(new THREE.TetrahedronGeometry(70), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); tetrahedron.position.x = 100; tetrahedron.position.y = 150; tetrahedron.position.z = -100; tetrahedron.castShadow = tetrahedron.receiveShadow = true; this.scene.add(tetrahedron); // 圓環 var torus = new THREE.Mesh(new THREE.TorusGeometry(70, 20, 16, 100), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); torus.rotation.y = -Math.PI / 2; torus.position.x = 100; torus.position.y = 150; torus.position.z = 100; torus.castShadow = torus.receiveShadow = true; this.scene.add(torus); // 圓環管 var torusK = new THREE.Mesh(new THREE.TorusKnotGeometry(70, 20, 16, 100), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); torusK.rotation.y = -Math.PI / 2; torusK.position.x = 100; torusK.position.y = 150; torusK.position.z = 300; torusK.castShadow = torusK.receiveShadow = true; this.scene.add(torusK); // 不規則的圓環結管 var points = []; for (var i = 0; i < 10; i++) { var randomX = -100 + Math.round(Math.random() * 200); var randomY = -100 + Math.round(Math.random() * 200); var randomZ = -100 + Math.round(Math.random() * 200); points.push(new THREE.Vector3(randomX, randomY, randomZ)); } var tube = new THREE.Mesh(new THREE.TubeGeometry(new THREE.SplineCurve3(points), 64, 20), new THREE.MeshLambertMaterial({ color: this.getRandColor() })); tube.rotation.y = -Math.PI / 2; tube.position.x = 0; tube.position.y = 500; tube.position.z = 0; tube.castShadow = tube.receiveShadow = true; this.scene.add(tube);
注意構造管過程,TubeGeometry 容許咱們經過一組點創建一個圓柱形物體。
爲了順利地將光,咱們只須要在update
方法裏添加如下代碼:
var timer = Date.now() * 0.000025; particleLight.position.x = Math.sin(timer * 5) * 300; particleLight.position.z = Math.cos(timer * 5) * 300;
未完待續~