Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Three.js Cookbook

You're reading from   Three.js Cookbook Over 80 shortcuts, solutions, and recipes that allow you to create the most stunning visualizations and 3D scenes using the Three.js library

Arrow left icon
Product type Paperback
Published in Jan 2015
Publisher Packt
ISBN-13 9781783981182
Length 300 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Jos Dirksen Jos Dirksen
Author Profile Icon Jos Dirksen
Jos Dirksen
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

Preface 1. Getting Started 2. Geometries and Meshes FREE CHAPTER 3. Working with the Camera 4. Materials and Textures 5. Lights and Custom Shaders 6. Point Clouds and Postprocessing 7. Animation and Physics Index

Getting started with the WebGL renderer

When you want to create an initial Three.js project that uses WebGL for rendering, you always have to set up the same couple of variables. You need a THREE.WebGLRenderer object, a THREE.Scene object, a camera, and some way to render the scene. In this recipe, we'll provide you with a standard template that you can use in your own projects to quickly get started with the WebGL renderer.

Getting ready

Make sure that you download the sources for this book. You can either do this in the following two ways:

  • Firstly, you can do this by cloning the Git repo that you can find at https://github.com/josdirksen/threejs-cookbook.
  • Alternatively, you can download the sources from Packt Publishing website. When you extract the ZIP file or clone the repository you'll find a set of directories; one for each chapter of this book. For this recipe, you can use 0 as a reference.

You can directly view the end result of this recipe by opening the previously mentioned file in your browser. When you open this example in the browser, you'll see the following screenshot:

Getting ready

This is a minimal scene, rendered with the THREE.WebGLRenderer object.

How to do it...

Creating a skeleton that you can use as a base for your projects is easy. With a couple of simple steps, you'll get your first WebGLRenderer-based Three.js scene up and running:

  1. Let's first define the basic HTML that we'll use:
    <!DOCTYPE html>
    <html>
      <head>
        <title>01.01 - WebGLRenderer - Skeleton</title>
        <script src="../libs/three.js"></script>
        <style>
          body {
          margin: 0;
          overflow: hidden;
          }
        </style>
      </head>
      <body>
        <script>
          ...
        </script>
      </body>
    </html>

    Tip

    Downloading the example code

    You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    As you can see this is use a simple page, with a script tag in the body that'll contain our Three.js code. The only interesting part is the CSS style.

    We will add this style to the body element to make sure that our Three.js scene will run in fullscreen mode and won't show any scrollbars.

  2. Next, let's start by filling in the script tag. The first thing that we will do is create a number of global variables that are used throughout this recipe:
          // global variables
          var renderer;
          var scene;
          var camera;

    The renderer variable will hold a reference to the THREE.WebGLRenderer object that we're going to create in the next step. The scene variable is the container for all the objects that we want to render, and the camera variable determines what we will see when we render the scene.

  3. Usually, you'd want to wait for all the HTML elements to finish loading, before you start running your JavaScript. For this, we use the following JavaScript:
          // calls the init function when the window is done loading.
          window.onload = init;

    With this code, we tell the browser to call the init function, once the complete page has loaded. In the next step, we'll show the content of this init function.

  4. For your skeleton to work, you need to add the init function, which looks as follows:
    function init() {
    
          // create a scene, that will hold all our elements 
          // such as objects, cameras and lights.
          scene = new THREE.Scene(); 
          // create a camera, which defines where we looking at.
          camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
          // position and point the camera to the center
          camera.position.x = 15;
          camera.position.y = 16;
          camera.position.z = 13;
          camera.lookAt(scene.position);
    
          // create a renderer, set the background color and size
          renderer = new THREE.WebGLRenderer();
          renderer.setClearColor(0x000000, 1.0);
          renderer.setSize(window.innerWidth, window.innerHeight);
    
          // create a cube and add to scene
          var cubeGeometry = new THREE.BoxGeometry(10 * Math.random(), 10 * Math.random(), 10 * Math.random());
    
          var cubeMaterial = new THREE.MeshNormalMaterial();
    
          var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
          scene.add(cube);
    
          // add the output of the renderer to the html element
          document.body.appendChild(renderer.domElement);
    
          // call the render function
          renderer.render(scene, camera);
    
          }

    In this init function, we first created a THREE.Scene object with the container for all the objects that we want to render. Next, we created a camera, which determines the field of the view that will be rendered. Next, we created the THREE.WebGLRenderer object, which is used to render the scene using WebGL. The THREE.WebGLRenderer object has many properties. In this recipe, we used the setClearColor property to set the background of our scene to black, and we told the renderer to use the complete window for its output, using the window.innerWidth and window.innerHeight properties. To see whether our skeleton page is working, we then added a simple THREE.Mesh object with a THREE.BoxGeometry object to the scene. At this point, we can add the output of the WebGL, as a child of the HTML body element. We do this by appending the renderer's DOM element to the document body. Now, all that is left to do is render the scene by calling renderer.render().

With these steps, you've created a basic WebGLRenderer based Three.js scene, which you can use as a basic starting point for all your Three.js experiments.

See also

  • The THREE.WebGLRenderer object only works when your browser supports WebGL. Even though most modern desktop browsers (and even a large number of mobile browsers) support WebGL, in some cases, you might need to look for an alternative. Three.js provides a couple of other renderers, which you can use. To get an up-to-date overview of which browsers support WebGL, you can check out the information on this topic at http://caniuse.com/webgl.
  • Besides using the THREE.WebGLRenderer object to render your scene, you can use the THREE.CanvasRenderer object, which is explained in Getting started with the Canvas renderer recipe or the THREE.CSS3DRenderer object, which is explained in the Getting started with the CSS 3D renderer recipe.
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image