ThreeJs Tutorial

What is Three.JS?

Three.js is a cross-browser JavaScript library and application programming interface that uses WebGL to create and display animated 3D computer graphics in a web browser. The source code is available in a GitHub repository.

The purpose of this section is to provide a brief overview of three.js. We'll begin by creating a scene with a spinning cube. If you get stuck and need assistance, a working example is provided at the bottom of the page.

Before you can use three.js, you must first find a place to display it. Open your browser and save the following HTML to a file on your computer, along with a copy of three.js in the js/ directory.

<!DOCTYPE html>
<html>
          <head>
                   <meta charset="utf-8">
                   <title>My first three.js app</title>
                   <style>
                             body { margin: 0; }
                   </style>
          </head>
          <body>
                   <script src="js/three.js"></script>
                   <script>
                             // Our Javascript will go here.
                   </script>
          </body>
</html>

That's all. All the code below goes into the empty <script> tag.

Creating The Scene

We'll need three things to display anything with three.js: a scene, a camera, and a renderer to draw the scene using the camera.

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

Let's take a step back and explain what's going on. We've finished setting up the scene, camera, and renderer.

Three.js has a number of various cameras. Let's utilise a PerspectiveCamera for now.

The field of view is the initial property. The field of view (FOV) refers to the size of the scene that can be viewed on the screen at any given time. Degrees are used to express the value.

The aspect ratio is the second. You nearly always want to divide the element's width by its height, else you'll get the same effect as when watching old movies on a widescreen TV: the image will appear compressed.

The near and far clipping planes are the next two properties. Objects that are farther away from the camera than the value of far or closer than the value of near will not be depicted. You don't need to worry about it right now, but you might want to experiment with different variables in your apps to improve performance.

The renderer comes next. It's here that the magic happens. In addition to the WebGLRenderer we're using here, three.js includes a few others that are frequently used as fallbacks for people with outdated browsers or who don't have WebGL support for whatever reason.

In addition to creating the renderer instance, we must also provide the size at which our app should be rendered. The width and height of the area we want to fill with our app - in this case, the width and height of the browser window - is a good idea. For performance-critical apps, lesser setSize values, such as window.innerWidth/2 and window.innerHeight/2, can be used to make the app render at quarter-size.

If you want to preserve your app's size while rendering it at a lesser resolution, call setSize with false as updateStyle (the third argument).

Let’s add the cube we planned to!

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;

A BoxGeometry is required to make a cube. This is an object that has all of the cube's points (vertices) and fill (faces). We'll dig deeper into this in the future.

We'll need a material to color it in addition to the geometry. Three.js comes with a variety of materials, but for now, we'll stick with MeshBasicMaterial. Every material is given a set of qualities that will be applied to it. We simply provide a color attribute of 0x00ff00, which is green, to keep things simple. This operates in the same way as CSS or Photoshop colors do (hex colors).

A Mesh is the third thing we require. A mesh is a type of object that takes a geometry and applies a material to it, allowing us to place it in our scene and move it about freely.

When we call scene.add(), the stuff we add is added to the coordinates by default (0,0,0). Both the camera and the cube would be trapped inside each other as a result of this. We simply move the camera out a little to avoid this.

Rendering the Scene

You wouldn't be able to see anything if you pasted the code from above into the HTML file we produced before. This is due to the fact that we haven't yet rendered anything. We'll need something called a render or animate loop for this.

function animate() {
          requestAnimationFrame( animate );
          renderer.render( scene, camera );
}
animate();

This will cause the renderer to draw the scene every time the screen is refreshed, resulting in a loop (on a typical screen this means 60 times per second). If you're new to web game development, you might think to yourself, "Why don't we just construct a setInterval?" Actually, we could, but requestAnimationFrame provides a few advantages. The most crucial benefit is that it stops when the user switches to another browser tab, preventing the user from squandering valuable processing power and battery life.

Animating the Cube

If you paste all of the above code into the file you made before we started, you should see a green box. Let's spice things up a little by rotating everything.

In your animate function, place the following code directly above the renderer.render call:

cube.rotation.x += 0.01;
cube.rotation.y += 0.01;

This will be executed once every frame (normally 60 times per second) and will provide the cube with a nice rotation animation. Everything you want to move or change while the app is running must go through the animate loop. You can, of course, call other functions from there to avoid having an animate function with hundreds of lines.

Result:

Your first three.js application is now complete. It's straightforward, but you have to begin somewhere.

<!DOCTYPE html>
<html>
          <head>
                   <meta charset="utf-8">
                   <title>My first three.js app</title>
                   <style>
                             body { margin: 0; }
                   </style>
          </head>
          <body>
                   <script src="js/three.js"></script>
                   <script>
                             const scene = new THREE.Scene();
                             const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
                             const renderer = new THREE.WebGLRenderer();
                             renderer.setSize( window.innerWidth, window.innerHeight );
                             document.body.appendChild( renderer.domElement );
                             const geometry = new THREE.BoxGeometry();
                             const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
                             const cube = new THREE.Mesh( geometry, material );
                             scene.add( cube );
                             camera.position.z = 5;
                             function animate() {
                                      requestAnimationFrame( animate );
                                      cube.rotation.x += 0.01;
                                      cube.rotation.y += 0.01;
                                      renderer.render( scene, camera );
                             };
                             animate();
                   </script>
          </body>
</html>

Three.js Tutorial Index


Related Topics

ThreeJS Geometries-1

BoxGeometry BoxGeometry is a geometry class for a rectangular cuboid with a given 'width', 'height', and 'depth'. On creation, the cuboid is centered on the origin, with each edge parallel to...

7 minutes read.

ThreeJS Property Binding and Mixer

PropertyBinding Internally, this holds a reference to real property in the scene graph. Constructor PropertyBinding( rootNode : Object3D, path, parsedPath ) -- rootNode: -- path -- parsedPath (optional) Properties The properties are as follows: .path : Number.parsedPath...

2 minutes read.

ThreeJS Testing with npm

This article explains how to install three.js in a node.js environment so that automated tests may be run. Tests can be done manually or with the help of automated CI...

4 minutes read.

ThreeJS Managers

DefaultLoadingManager When no custom manager is specified, most loaders use a global instance of the LoadingManager. This will suffice for most purposes, but there may be times when you want separate loading...

4 minutes read.

ThreeJS Scenes

Fog This class contains the parameters that define linear fog, i.e., that grows linearly denser with the distance. Constructor Fog( color : Integer, near : Float, far : Float ) The color parameter is...

3 minutes read.

ThreeJS Helper 1

ArrowHelper A 3D arrow object for visualizing directions. Code Example const dir = new THREE.Vector3( 1, 2, 0 ); //normalize the direction vector (convert to vector of length 1) dir.normalize(); const origin = new THREE.Vector3( 0,...

5 minutes read.

ThreeJs Tutorial

What is Three.JS? Three.js is a cross-browser JavaScript library and application programming interface that uses WebGL to create and display animated 3D computer graphics in a web browser. The source code...

6 minutes read.

ThreeJS Loader 1

AnimationLoader Class for loading AnimationClips in JSON format. This uses the FileLoader internally for loading files. Code Example // instantiate a loader const loader = new THREE.AnimationLoader(); // load a resource loader.load( // resource URL 'animations/animation.js', // onLoad callback function...

8 minutes read.

ThreeJS AnimationObjectGroup and Utils

AnimationObjectGroup A group of objects that receives a shared animation state. Usage Add items you'd normally send as 'root' to AnimationMixer's function Object() { [native code] } or clipAction method, and instead pass...

2 minutes read.

ThreeJS Keyframe Track

A KeyframeTrack is a timed series of keyframes that are made up of lists of times and related values and are used to animate an object's unique property. The "Animation System"...

4 minutes read.

ThreeJS Interpolant

CubicInterpolant Code Example const interpolant = new THREE.CubicInterpolant(new Float32Array( 2 ),new Float32Array( 2 ),1,new Float32Array( 1 ));interpolant.evaluate( 0.5 ); Constructor CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) parameterPositions -- array of positions sampleValues -- array of samples sampleSize...

2 minutes read.

ThreeJS Objects

Bone A bone that is part of a Skeleton. The skeleton in turn is used by the SkinnedMesh. Bones are almost identical to a blank Object3D. Code Example const root = new THREE.Bone(); const...

12 minutes read.

ThreeJS Material - Mesh

MeshBasicMaterial A material for drawing geometries in a simple shaded (flat or wireframe) way. This material is not affected by lights. Constructor MeshBasicMaterial( parameters : Object ) parameters - (optional) an object with one or...

24 minutes read.

ThreeJS BufferGeometry

A mesh, line, or point geometry representation. Included within buffers are vertex positions, face indices, normals, colours, UVs, and custom attributes, lowering the cost of passing all of this data...

5 minutes read.

ThreeJS Updating Things

If an item has been added to the scene with the specified code, it will immediately update its matrices. const object = new THREE.Object3D(); scene.add( object ); or, if they are the child...

4 minutes read.

ThreeJS Cameras

ArrayCamera ArrayCamera can be used to render a scene using a preset group of cameras quickly. This is an important feature of VR scene rendering performance. An array of sub cameras is...

6 minutes read.

ThreeJS Object3D

This is the base class for most three.js objects, and it provides a set of properties and methods for manipulating objects in 3D space. It should be noted that this can...

9 minutes read.

ThreeJS AnimationAction

AnimationActions are used to schedule the playback of animations saved in AnimationClips. Note that the majority of AnimationAction's methods can be chained together. The "Animation System" page in the "Next Steps" part...

6 minutes read.

ThreeJS Loaders 2

ImageBitmapLoader A loader that converts an image to an ImageBitmap. An ImageBitmap provides an asynchronous and resource-efficient path for preparing textures for WebGL rendering. ImageBitmapLoader, unlike FileLoader, does not prevent multiple concurrent...

8 minutes read.

ThreeJS Loading 3D Models

There are hundreds of file formats for 3D models, each with its own purpose, set of features, and level of complexity. Although three.js has a lot of loaders, choosing the...

2 minutes read.