Tutorial 03: Adding color Tutorial 05: 3D shapes   

 

Tutorial 04: Rotation

This tutorial assumes, that you have read and understood lesson 03.
This lesson teaches you how to apply transformations and animations to objects in the scene.
To see the lessons result, you can jump to the live example
 
WebGL
Screenshot of the WebGL renderer
Chrome Firefox Safari Opera Internet Explorer
WebGL
Screenshot of the canvas renderer
Advertisement
 
Tutorial
  1 <!DOCTYPE html> 
  2 <!-- The previous line tells the browser, that the page uses the HTML5 standard. --> 
  3  
  4 <html>
  5     <head>
  6         <title>Three.js tutorial - Lesson 04</title> 
  7         <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> 
  8  
  9         <!-- The following meta line optimizes the site for mobile devices. It sets the viewport size 
 10         to the screen size, so it will be displayed maximized, but unscaled. --> 
 11         <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1"> 
 12         <style type="text/css"> 
 13             body { 
 14                 /* Set the background color of the HTML page to black */ 
 15                 background-color: #000000; 
 16  
 17                 /* Hide oversized content. This prevents the scroll bars. */ 
 18                 overflow: hidden; 
 19             } 
 20         </style> 
 21         <!-- Include Three.js libraries --> 
 22         <script src="../js/r69/three.js"></script> 
 23         <script src="../js/r69/Detector.js"></script> 
 24         <script src="../js/r69/CanvasRenderer.js"></script> 
 25         <script src="../js/r69/Projector.js"></script> 
 26     </head> 
 27     <body>
 28         <!-- This is the DIV element which will contain the WebGL canvas. To be identifiable lateron, 
 29         the id 'WebGLCanvas' is applied to it. --> 
 30         <div id="WebGLCanvas"> 
 31  
 32         <!-- This JavaScript block encloses the Three.js commands --> 
 33         <script> 
 34             // Global scene object 
 35             var scene; 
 36  
 37             // Global camera object 
 38             var camera; 
 39  
 40             // Global mesh object of the triangle 
 41             var triangleMesh; 
 42  
 43             // Global mesh object of the square 
 44             var squareMesh; 
 45  
 46             // Initialize the scene 
 47             initializeScene(); 
 48  
 49             // Instead of calling 'renderScene()', we call a new function: 'animateScene()'. It will 
 50             // update the rotation values and call 'renderScene()' in a loop. 
 51  
 52             // Animate the scene 
 53             animateScene(); 
 54  
 55             /** 
 56              * Initialze the scene. 
 57              */ 
 58             function initializeScene(){ 
 59                 // Check whether the browser supports WebGL. If so, instantiate the hardware accelerated 
 60                 // WebGL renderer. For antialiasing, we have to enable it. The canvas renderer uses 
 61                 // antialiasing by default. 
 62                 // The approach of multiplse renderers is quite nice, because your scene can also be 
 63                 // viewed in browsers, which don't support WebGL. The limitations of the canvas renderer 
 64                 // in contrast to the WebGL renderer will be explained in the tutorials, when there is a 
 65                 // difference. 
 66                 if(Detector.webgl){ 
 67                     renderer = new THREE.WebGLRenderer({antialias:true}); 
 68  
 69                 // If its not supported, instantiate the canvas renderer to support all non WebGL 
 70                 // browsers 
 71                 } else { 
 72                     renderer = new THREE.CanvasRenderer(); 
 73                 } 
 74  
 75                 // Set the background color of the renderer to black, with full opacity 
 76                 renderer.setClearColor(0x000000, 1); 
 77  
 78                 // Get the size of the inner window (content area) to create a full size renderer 
 79                 canvasWidth = window.innerWidth; 
 80                 canvasHeight = window.innerHeight; 
 81  
 82                 // Set the renderers size to the content areas size 
 83                 renderer.setSize(canvasWidth, canvasHeight); 
 84  
 85                 // Get the DIV element from the HTML document by its ID and append the renderers DOM 
 86                 // object to it 
 87                 document.getElementById("WebGLCanvas").appendChild(renderer.domElement); 
 88  
 89                 // Create the scene, in which all objects are stored (e. g. camera, lights, 
 90                 // geometries, ...) 
 91                 scene = new THREE.Scene(); 
 92  
 93                 // Now that we have a scene, we want to look into it. Therefore we need a camera. 
 94                 // Three.js offers three camera types: 
 95                 //  - PerspectiveCamera (perspective projection) 
 96                 //  - OrthographicCamera (parallel projection) 
 97                 //  - CombinedCamera (allows to switch between perspective / parallel projection 
 98                 //    during runtime) 
 99                 // In this example we create a perspective camera. Parameters for the perspective 
100                 // camera are ... 
101                 // ... field of view (FOV), 
102                 // ... aspect ratio (usually set to the quotient of canvas width to canvas height) 
103                 // ... near and 
104                 // ... far. 
105                 // Near and far define the cliping planes of the view frustum. Three.js provides an 
106                 // example (http://mrdoob.github.com/three.js/examples/ 
107                 // -> canvas_camera_orthographic2.html), which allows to play around with these 
108                 // parameters. 
109                 // The camera is moved 10 units towards the z axis to allow looking to the center of 
110                 // the scene. 
111                 // After definition, the camera has to be added to the scene. 
112                 camera = new THREE.PerspectiveCamera(45, canvasWidth / canvasHeight, 1, 100); 
113                 camera.position.set(0, 0, 10); 
114                 camera.lookAt(scene.position); 
115                 scene.add(camera); 
116  
117                 // Create the triangle (or any arbitrary geometry). 
118                 // 1. Instantiate the geometry object 
119                 // 2. Add the vertices 
120                 // 3. Define the faces by setting the vertices indices 
121                 var triangleGeometry = new THREE.Geometry(); 
122                 triangleGeometry.vertices.push(new THREE.Vector3( 0.0,  1.0, 0.0)); 
123                 triangleGeometry.vertices.push(new THREE.Vector3(-1.0, -1.0, 0.0)); 
124                 triangleGeometry.vertices.push(new THREE.Vector3( 1.0, -1.0, 0.0)); 
125                 triangleGeometry.faces.push(new THREE.Face3(0, 1, 2)); 
126  
127                 // To color the surface, a material has to be created. If all vertices shall have 
128                 // different colors, we need to set the vertex colors of each face. The colors in 
129                 // between will be interpolated as color gradients. 
130                 // Unfortunately, the canvas renderer doesn't support vertex yolors (yet [Three.js, 
131                 // release 50]). Either you accept a white face color, or set another face color. 
132  
133                 triangleGeometry.faces[0].vertexColors[0] = new THREE.Color(0xFF0000); 
134                 triangleGeometry.faces[0].vertexColors[1] = new THREE.Color(0x00FF00); 
135                 triangleGeometry.faces[0].vertexColors[2] = new THREE.Color(0x0000FF); 
136  
137                 // To activate the vertex color, we have to set 'vertexColors' attribute to 
138                 // 'THREE.VertexColors'. Otherwise they won't be displayed. 
139  
140                 // Create a basic material, supporting vertex colors. Activate the 'doubleSided' 
141                 // attribute to force the rendering of both sides of each face (front and back). 
142                 // This prevents the so called 'backface culling'. Usually, only the side is 
143                 // rendered, whose normal vector points towards the camera. The other side is not 
144                 // rendered (backface culling). But this performance optimization sometimes leads 
145                 // to wholes in the surface. When this happens in your surface, simply set 
146                 // 'doubleSided' to 'true'. 
147                 var triangleMaterial = new THREE.MeshBasicMaterial({ 
148                     vertexColors:THREE.VertexColors, 
149                     side:THREE.DoubleSide 
150                 }); 
151  
152                 // Create a mesh and insert the geometry and the material. Translate the whole mesh 
153                 // by -1.5 on the x axis and by 4 on the z axis. Finally add the mesh to the scene. 
154                 triangleMesh = new THREE.Mesh(triangleGeometry, triangleMaterial); 
155                 triangleMesh.position.set(-1.5, 0.0, 4.0); 
156                 scene.add(triangleMesh); 
157  
158                 // The creation of the square is done in the same way as the triangle, except of the 
159                 // face definition. Instead of using one THREE.Face3, we have to define two 
160                 // THREE.Face3 objects. 
161                 // 1. Instantiate the geometry object 
162                 // 2. Add the vertices 
163                 // 3. Define the faces by setting the vertices indices 
164                 var squareGeometry = new THREE.Geometry(); 
165                 squareGeometry.vertices.push(new THREE.Vector3(-1.0,  1.0, 0.0)); 
166                 squareGeometry.vertices.push(new THREE.Vector3( 1.0,  1.0, 0.0)); 
167                 squareGeometry.vertices.push(new THREE.Vector3( 1.0, -1.0, 0.0)); 
168                 squareGeometry.vertices.push(new THREE.Vector3(-1.0, -1.0, 0.0)); 
169                 squareGeometry.faces.push(new THREE.Face3(0, 1, 2)); 
170                 squareGeometry.faces.push(new THREE.Face3(0, 2, 3)); 
171  
172                 // The square gets a new face color. In contrast to vertex colors means face color, 
173                 // that all vertices have the same color or in other words, the whole face has the 
174                 // same color (no color gradients). 
175  
176                 // Create a light blue basic material and activate the 'doubleSided' attribute. 
177                 var squareMaterial = new THREE.MeshBasicMaterial({ 
178                     color:0x8080FF, 
179                     side:THREE.DoubleSide 
180                 }); 
181  
182                 // Create a mesh and insert the geometry and the material. Translate the whole mesh 
183                 // by 1.5 on the x axis and by 4 on the z axis and add the mesh to the scene. 
184                 squareMesh = new THREE.Mesh(squareGeometry, squareMaterial); 
185                 squareMesh.position.set(1.5, 0.0, 4.0); 
186                 scene.add(squareMesh); 
187             } 
188  
189             /** 
190              * Animate the scene and call rendering. 
191              */ 
192             function animateScene(){ 
193                 // At first, we increase the y rotation of the triangle mesh and decrease the x 
194                 // rotation of the square mesh. 
195              
196                 // Increase the y rotation of the triangle 
197                 triangleMesh.rotation.y += 0.1; 
198  
199                 // Decrease the x rotation of the square 
200                 squareMesh.rotation.x -= 0.075; 
201  
202                 // Define the function, which is called by the browser supported timer loop. If the 
203                 // browser tab is not visible, the animation is paused. So 'animateScene()' is called 
204                 // in a browser controlled loop. 
205                 requestAnimationFrame(animateScene); 
206  
207                 // Map the 3D scene down to the 2D screen (render the frame) 
208                 renderScene(); 
209             } 
210  
211             /** 
212              * Render the scene. Map the 3D world to the 2D screen.
213              */ 
214             function renderScene(){ 
215                 renderer.render(scene, camera); 
216             } 
217         </script> 
218     </body> 
219 </html>
Live example