Three.js – Quick Guide


Table of Contents

Three.js – Quick Guide



”;


Three.js – Introduction

All modern browsers became more powerful and more accessible directly using JavaScript. They have adopted WebGL (Web Graphics Library), a JavaScript API, which allows you to render highperformance interactive 3D and 2D graphics within any compatible web browser using the capabilities of the GPU (Graphics Processing Unit).

But WebGL is a very low-level system that only draws basic objects like point, square, and line. However, programming WebGL directly from JavaScript is a very complex and verbose process. You need to know the inner details of WebGL and learn a complex shader language to get the most out of WebGL. Here comes Three.js to make your life easy.

What is Three.js?

Three.js is an open-source, lightweight, cross-browser, general-purpose JavaScript library. Three.js uses WebGL behind the scenes, so you can use it to render Graphics on an HTML <canvas> element in the browser. Since Three.js uses JavaScript, you can interact with other web page elements, add animations and interactions, and even create a game with some logic.

Why use Three.js?

The following features make Three.js an excellent library to use.

  • You can create complex 3D graphics by just using JavaScript.

  • You can create Virtual Reality (VR) and Augmented Reality (AR) scenes inside the browser.

  • Since it uses WebGL, it has cross-browser support. Many browsers support it.

  • You can add various materials, textures and animate 3D objects.

  • You can also load and work on objects from other 3D modeling software.

With a couple of lines of JavaScript and simple logic, you can create anything, from highperformance interactive 3D models to photorealistic real-time scenes.

These are some excellent websites created using Three.js−

You can find many other examples on the official website of three.js

Browser Support

All modern browsers on desktop, as well as on mobile, currently support WebGL. The only browser where you have to take care of is the mobile Opera Mini browser. For IE 10 and older,there is the IEWebGL plugin, which you can get from https://github.com/iewebgl/iewebgl./ You can find detailed information about the WebGL browser support here.

Once you understand what Three.js is, you can continue to the next chapter about setting up a project to start working with Three.js.

Three.js – Installation

There are many ways to include Three.js in your project. You can use any of these following methods to get started using Three.js. Then open your favorite code editor and get going.

Download the complete Three.js project

Download the complete Three.js project into your system. You can download it here or from GitHub. Extract the three.js-master.zip file and look inside the build folder. You can find two three.js, three.min.js, which is just a minified version. Add any of these two files into your project folder and link them to your HTML file. Now you are good to use Three.js in your project.

Note − We recommend using the minified version as it loads faster.

Insert the following <script> tag into the <head> element of your HTML with a path to the threejs.min.js file.


<script src=''/path/to/threejs.min.js''></script>

Use CDN links

You can link the files from a CDN (Content Delivery Network), a remote site dedicated to hosting files so that you can use them online. You can use any of these websites −

Insert any of the following <script> tags into the <head> element of your HTML.


<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r127/three.min.js"></script>

or


<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>

Install the package of Three.js

Three.js is also available as a package on NPM.If you have Node.js set up on your computer, you can install it using npm or yarn.


npm install three

or


yarn add three

Then, you can import Three.js from the three.module.js file into your JavaScript file


import * as THREE from ''three''

You can use Three.js along with any JavaScript framework like React, Angular, Vue.

Once you finish setting up your project, let”s start creating.

Three.js – Hello Cube App

Like any other programming language, let”s start learning Three.js by creating “Hello cube!” app.

The HTML


<!DOCTYPE html>
<html>
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <meta charset="UTF-8" />
      <title>Three.js - Hello cube</title>
      <style>
         /* Our CSS goes here */
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r127/three.min.js"></script>
   </head>
   <body>
      <div id="threejs-container">
         <!-- Our output to be rendered here →
      </div>
      <script type="module">
         // our JavaScript code goes here
      </script>
   </body>
</html>

As you can see, it”s just a simple HTML file with Three.js CDN.

The CSS


<style>
* {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
   font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
   Oxygen,
   Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
html,
body {
   height: 100vh;
   width: 100vw;
}
#threejs-container{
   position: block;
   width: 100%;
   height: 100%;
}
</style>

The above CSS is just the basic styling of the HTML page. The threejs-container takes up the whole screen.

The JavaScript

This is where our three.js app comes into life. The code below renders a single cube in the middle of the screen. All these codes will go into the empty <script> tag in the HTML.


const width = window.innerWidth
const height = window.innerHeight
// Scene
const scene = new THREE.Scene()
scene.background = new THREE.Color(''#00b140'')
// Camera
const fov = 45 // AKA Field of View
const aspect = window.innerWidth / window.innerHeight
const near = 0.1 // the near clipping plane
const far = 100 // the far clipping plane
const camera = new PerspectiveCamera(fov, aspect, near, far)
camera.position.set(0, 0, 10)
// Renderer
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
// Creating a cube
const geometry = new THREE.BoxGeometry(2, 2, 2)
const material = new THREE.MeshBasicMaterial({ wireframe: true })
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
// Rendering the scene
const container = document.querySelector(''#threejs-container'')
container.append(renderer.domElement)
renderer.render(scene, camera)

Let”s discuss the code one step at a time, and then you can get more information about each element in the upcoming chapters. The first thing we need to do is to create a scene, a camera, and a renderer. These are the essential components that make up every Three.js app.

The Scene


const scene = new THREE.Scene()
scene.background = new THREE.Color(''#262626'')

The scene serves as the container for everything we can see on the screen, without a THREE.Scene object, Three.js cannot render anything. The background color is dark gray so that we can see the cube.

The Camera


const camera = new PerspectiveCamera(fov, aspect, near, far)
camera.position.set(0, 0, 10)

The camera object defines what we’ll see when we render a scene. There are not many but different types of cameras, but for this example, you’ll use a PerspectiveCamera, which matches the way our eyes see the world.

The Renderer


const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)

The renderer object is responsible for calculating what the scene looks like in the browser, based on the camera. There are different types of renderers, but we mainly use WebGLRenderer since most browsers support WebGL.

In addition to creating the renderer instance, we also need to set the size at which we want it to render our app. It”s a good idea to use the width and height of the area we want to fill with our app The Cube- in this case, the width and height of the browser window.

The Cube


const geometry = new THREE.BoxGeometry(2, 2, 2)
const material = new THREE.MeshBasicMaterial({
   color: 0xffffff,
   wireframe: true,
})
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)

The above code creates a simple cube at the center of the screen. We can make any object using THREE.Mesh. The Mesh takes two objects, geometry and material. The geometry of a mesh defines its shape, and materials determine the surface properties of objects.

To create a cube, we need BoxGeometry and a primary material (MeshBasicMaterial) with the color 0xffffff. If the wireframe property is set to true, it tells Three.js to show us a wireframe and not a solid object.

Rendering the Scene


const container = document.querySelector(''#threejs-container'')
container.append(renderer.domElement)
renderer.render(scene, camera)

Example

Last but not least, we add the renderer element to our HTML document. The renderer uses an <canvas> element to display the scene to us. In this case, the renderer appends the <canvas> element to the reference container in the HTML.

hello-cube-app.html


<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="ie=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Three.js – Hello cube</title>
      <style>
         * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -applesystem, BlinkMacSystemFont, ''Segoe UI'', Roboto, Oxygen, Ubuntu,
            Cantarell, ''Open Sans'', ''Helvetica Neue'', sans-serif;
         }
         html,
         body {
            height: 100vh;
            overflow: hidden;
            width: 100vw;
         }
         #threejs-container {
            position: block;
            width: 100%;
            height: 100%;
         }
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
   </head>
   <body>
      <div id="threejs-container"></div>
      <script type="module">
         // Hello Cube App
         // Your first Three.js application
         // sizes
         const width = window.innerWidth
         const height = window.innerHeight
         // scene
         const scene = new THREE.Scene()
         scene.background = new THREE.Color(0x262626)
         // camera
         const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100)
         camera.position.set(0, 0, 10)
         // cube
         const geometry = new THREE.BoxGeometry(2, 2, 2)
         const material = new THREE.MeshBasicMaterial({
            color: 0xffffff,
            wireframe: true
         })
         const cube = new THREE.Mesh(geometry, material)
         scene.add(cube)
         // renderer
         const renderer = new THREE.WebGL1Renderer()
         renderer.setSize(width, height)
         renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
         // rendering the scene
         const container = document.querySelector(''#threejs-container'')
         container.append(renderer.domElement)
         renderer.render(scene, camera)
      </script>
   </body>
</html>

Output

The output looks like this if everything is working correctly. Play around with the code to get a better understanding of how it works.