Book Image

Learning Three.js: The JavaScript 3D Library for WebGL

By : Jos Dirksen
Book Image

Learning Three.js: The JavaScript 3D Library for WebGL

By: Jos Dirksen

Overview of this book

<p>Three.js is a JavaScript 3D library that offers a wide range of features for creating and displaying stunning 3D computer graphics on a web browser in an intuitive manner using JavaScript without having to deal with the complexity of a WebGL low-level API. Even though WebGL makes it possible to create 3D graphics in the browser without having to use plugins, programming WebGL, however, is hard and complex. This book shows you how Three.js allows you to be independent of browser plugins.</p> <p>If you are an experienced web designer who wants to set the tone for an immersive design environment in your applications then this book is for you.<br /><br />"Learning Three.js: The JavaScript 3D Library for WebGL" is a practical, example-rich book that will help you to master all the features of Three.js. With this book, you’ll learn how to create and animate gorgeous looking 3D scenes directly in your browser utilizing the full potential of WebGL and modern browsers without having to learn WebGL.<br /><br />"Learning Three.js: The JavaScript 3D Library for WebGL" starts by going over the basic concepts and building blocks used in Three.js. From there on, it will expand on these subjects using extensive examples and code samples. This will allow you to learn everything you need to know about Three.js in an easy and interactive manner.</p> <p>Besides the basic concepts, this book will show you how you can create realistic looking 3D objects using materials and textures as well as how to load them from externally created models. You’ll learn how to easily control the camera using the Three.js build-in camera controls so you can fly or walk around the 3D scene you have created. You will also learn how to use morph and bones-based animation and how to add physics to your scene.</p> <p>After reading Learning Three.js: The JavaScript 3D Library for WebGL and playing around with the extensive set of examples, you’ll know everything that is required to create 3D animating graphics using Three.js that run in any browser.</p>
Table of Contents (20 chapters)
Learning Three.js: The JavaScript 3D Library for WebGL
Credits
About the Author
Acknowledgement
About the Reviewers
www.PacktPub.com
Preface
8
Creating and Loading Advanced Meshes and Geometries
Index

Rendering and viewing a 3D object


In this step you'll create your first scene and add a couple of objects and a camera. Our first example will contain the following objects:

Object

Description

Plane

A two-dimensional rectangle that serves as our ground area. This is rendered as the gray rectangle in the middle of the scene.

Cube

A three-dimensional cube, which we'll render in red

Sphere

A three-dimensional sphere, which we'll render in blue

Camera

The camera determines what you'll see in the output

Axes

x, y, and z axes. This is a helpful debugging tool to see where the objects are rendered.

I'll first show you how this looks in code (the source file with comments can be found in the chapter-01 folder and is labeled 02-first-scene.html) and then I'll explain what's happening:

<script type="text/javascript">

    
    $(function () {
        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(0xEEEEEE);
        renderer.setSize(window.innerWidth, window.innerHeight);

        var axes = new THREE.AxisHelper( 20 );
        scene.add(axes);

        var planeGeometry = new THREE.PlaneGeometry(60,20,1,1);
        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.CubeGeometry(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 = 2;

        scene.add(sphere);

        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        $("#WebGL-output").append(renderer.domElement);
        renderer.render(scene, camera);
    });

If we open this example in the browser, we will see something that resembles what we're aiming for, but is still a long way off:

Before we start making this more beautiful, I'll first walk you through the code a step at a time so that you understand what the code does:

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(0xEEEEEE);
renderer.setSize(window.innerWidth, window.innerHeight);

Prior to the given example we defined a scene, a camera, and a renderer. The scene variable is a container that is used to store and keep track of all the objects that we want to render. The sphere and the cube that we want to render will be added to this scene later on in the example. In this first fragment, we also create a camera variable. The camera variable defines what we'll see when we render the scene. In Chapter 2, Working with the Basic Components That Make Up a Three.js Scene, you will learn more about the arguments that you can pass into the camera. Next, we will define a renderer object. The renderer is responsible for calculating what the scene will look like in the browser based on the camera angle. We will create a WebGLRenderer object in this example that will use your graphics card to render the scene.

Tip

If you look through the source code and the documentation of Three.js. you'll notice that there are different renderers available besides the WebGL-based one. There is a canvas-based renderer and even an SVG-based one. Even though they work and can render simple scenes, I wouldn't recommend using them. They're very CPU-intensive and lack features such as good material support and shadows.

Here we set the background color of the renderer to almost white (0XEEEEEE) with the setClearColorHex() function and tell the renderer how large the scene needs to be rendered by using the setSize() function.

So far, we've got a basic empty scene, a renderer, and a camera. There is, however, nothing yet to render. The following code adds the helper axes and the plane.

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);

As you can see, we have created an axes object and used the scene.add() function to add these axes to our scene. Now we will create the plane. This is done in two steps. First we define what the plane looks like using the new THREE.PlaneGeometry(60,20) code. In this case it has a width of 60 and a height of 20. We also need to tell Three.js what this plane looks like (for example, its color and its transparency). In Three.js we do this by creating a material object. For this first example we'll create a basic material (by using the MeshBasicMaterial() method) with the color 0xcccccc. Next we combine these two into a Mesh object with the name plane. Before we add this plane to the scene we need to put it in the correct position; we do this by first rotating it 90 degrees around the x axis and next we defining its position in the scene by using the position property. If you're already interested in the details of the Mesh object, look at example 06-mesh-properties.html from Chapter 2, Working with the Basic Components That Make Up a Three.js Scene, which shows and explains rotation and positioning. The final step that we need to do is add this plane to the scene, just like we did with the axes.

The cube and sphere are added in the same manner, but with the wireframe property set to true, so let's move on to the final part of this example:

camera.position.x = -30;
camera.position.y = 40;
camera.position.z = 30;
camera.lookAt(scene.position);

$("#WebGL-output").append(renderer.domElement);
renderer.render(scene, camera);

At this point all the elements that we want to render are added to the scene at the correct positions. I've already mentioned that the camera defines what will be rendered. In this piece of code we position the camera using the x, y, and z position attributes to hover above our scene. To make sure that the camera is looking at our objects, we use the lookAt() function to point it at the center of our scene. All that is left to do is append the output from the renderer to the <div> element of our HTML skeleton; we use jQuery to select the correct output element, and tell the renderer to render the scene using the provided camera.

In the next couple of sections, we'll make this scene more pretty by adding lights, more materials, and even animations.