The Easiest Way to Get Started with Three.js Web Animations

Patricia Arnedo
JavaScript in Plain English
8 min readJan 22, 2024

--

The animation rabbit hole is a deep one, covering a set of nearly endless subjects that collectively shape the world of motion graphics. So yea, it’s hard to find a starting point that will quickly result in making your own animations before you die of old age learning about the necessary technology and software. Add web development into the mix, and now you have two endless rabbit holes of information, techniques, tools and concepts to overcome.

A rotating dodecahedron wireframe with a solid, iridescent animated dodecahedron inside.

Suffice it to say, it’s easy to feel overwhelmed when trying to decide what to learn first. So instead, let this tutorial be your blinders. Contained here is the bare minimum knowledge that you need to understand how web animations with three.js work, and how to animate something in your browser right now, in just 5 easy steps. (That’s right! Just 5 easy steps!)

Are you sold? Good. Let’s get started. The first section is a topical overview of the core elements of three.js. If you already know that much, skip to the tutorial.

What is Three.js?

Three.js is a javascript library and API designed for generating and displaying animations in web browsers. It uses WebGL, a low level API that is fully integrated with web standards, to execute code on a computer’s GPU. Since its release in 2010, three.js has become a popular library that makes it easy to add animations to web pages without plug-ins or applications.

Three.js Basics

The core function of three.js is to create animated scenes with various elements. The Scene, Camera, and Renderer objects are its core elements. The Scene object is like a container for animated shapes, and the Camera defines what you see when your animation is rendered. You might often see the word frustum in reference to the Camera, think of it as the shape of what the camera sees, which you can define according to your needs.

There is a pyramid coming out of a camera, the tip os oriented towards the camera. There is a highlighted area where the tip of the Pyramid is cut off. The shape of the truncated pyramid is the camera’s frustum.
The highlighted shape in the above image is the camera’s frustum. Take note of the near and far planes.

Scene and Camera objects are passed to a Renderer, which ‘draws’ the objects within the camera’s field of view and projects them onto a canvas in the browser. The following objects are the basic elements of a scene:

Geometry

A Geometry is a shape represented as vertex data. Three.js provides primitives like cubes, spheres, cones, cylinders and planes. You can create custom geometries, or import them from other sources.

Material

A Material provides surface properties for a Geometry. Material objects define properties like color and sheen, which are built in and can be customized. A Material can reference a Texture object to provide more detail and customization.

Texture

A Texture is an image used for the surface of a Geometry. You can think of this as wrapping paper for a given shape. It is referenced via a Material, and can be loaded from files or generated by a canvas or 3D scene.

Mesh

A Mesh unites Geometry and Material objects to create a shape with the surface properties defined by the Material. This combination of Geometry and Material is what you will see rendered in your animation as a single shape. For example, if there is an orange sphere in your scene, it is a Mesh that has been passed a SphereGeometry object and a Material with an orange color property. Geometry and Material objects can be referenced by multiple Mesh objects.

Light

Light is exactly what it sounds like, an object that illuminates your scene so that it becomes visible. Light objects can be directional or ambient lighting, and can illuminate different parts of a scene depending on brightness and proximity.

The Structure of a Scene

You can conceptualize a Scene as a tree-like structure with parent/child relationships. The Scene object is the root of the tree, and provides properties like background color and ambient effects. Geometry, Material, and Texture objects are children nodes, and will be positioned relative to their parent node.

This is a diagram of the elements in a scene and how they relate to each other. There are three parts to it, the WebGLRenderer, which is at the top and not connected to anything. Next to it is the Camera, which is also not connected to anything. Below these is the Scene, which has a tree like structure. It has a Mesh as a child node. The Mesh has two child nodes, one is a BoxGeomtry, and the other a Material.
The structure of a basic three.js scene, or scenegraph.

We will now use these basic elements to create and render a scene.

Tutorial

Scope

This tutorial covers installing three.js, creating a new project, generating a simple scene, and displaying it in a browser. By the end of this you will have created a scene with a rotating 3D shape, the “Hello World!” equivalent that provides the foundation for more complex scenes and animations.

Requirements

This tutorial assumes that you are familiar with ES6 style Javascript and Node.js environments for web development. It also assumes that you read the Three.js Basics section above. If you didn’t, you can look up the terms in that section as you go along, I made them easy to find because I get it, I’m impatient too. I use Vite as a build tool here, which requires Node.js version 18+. Modern, up to date browsers like Safari, Chrome, and Firefox support WebGL and should have no issue displaying your application. A linter is recommended.

Step 1: Install Dependencies and Serve Your App Locally

  1. Open Visual Studio code or your editor of choice to an empty directory and open a terminal session.
  2. Initialize a project that can handle dependencies using Vite like so:
npm create vite@latest

Enter a project name and package name when prompted. Select Vanilla from the list of frameworks then select Javascript. This will initialize a Javascript project with a main.js file and a package.json file for installing dependencies. Follow the instructions provided to complete setup.

3. Install three.js:

npm install three

4. Serve your application to view it in a browser:

npm run dev

Step 2: Add a Canvas for Your 3D Scene

First, let’s clear the default formatting to make way for our own styling and content.

  1. Go to the style.css file and delete boilerplate CSS.
  2. Go to the main.js file and delete boilerplate code.
  3. Go to the index.html file and add a canvas element in the body, which will display your animation. Include it before the main.js script and give it an id:
<canvas id=”bg”></canvas>

4. Style the canvas in the style.css file. Give it a fixed position and pin it to the top left corner of the screen:

canvas {
position: fixed;
top: 0;
left: 0;
}

The Javascript project you created is now ready for you to begin building with three.js!

Step 3: Create the Foundation for Your Scene

This part can seem intimidating, but it really just consists of copying the following code into your editor. It seeems like a lot of steps, but half of them are copy and paste and will take you 30 seconds. Even if you don’t understand everything right away, it will begin to make sense as you piece the elements together and see your changes in the browser. If you need clarification on what is happening you can always consult the docs for more in-depth explanations.

  1. Go to main.js and import styles and three.js:
import “./style.css”;
import * as THREE from “three”;

2. Instantiate a Scene:

const scene = new THREE.Scene();

3. Instantiate the Camera object. Three.js has several types of cameras, the most common of which is the PerspectiveCamera, which simulates the way our eyes perceive objects. PerspectiveCamera has the following properties:

  • field of view: The vertical height of the camera’s field of view
  • aspect: The camera’s aspect ratio
  • near : The camera frustum’s near plane
  • far: The camera frustum’s far plane

Define the camera with the following parameters:

  • fov: 75
  • aspect: window.innerwidth / window.innerheight (Uses the browser window to calculate the aspect ratio)
  • near: 0.1
  • far: 1000 (These near and far values allow us to see everything in front of our camera.)

And now in code:

const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);

4. Instantiate the Renderer and pass in the DOM element that we want the scene to be rendered in:

const renderer = new THREE.WebGLRenderer({
canvas: document.querySelector(“#bg”),
});

5. In order to support high resolution screens, set the pixel ratio according to the device pixel ratio:

renderer.setPixelRatio(window.devicePixelRatio);

6. To have a fullscreen view of the scene, set the renderer size as well:

renderer.setSize(window.innerWidth, window.innerHeight);

7. Set the Camera position on the Z axis to make it easier to see the scene:

camera.position.z = 30;

8. Lastly, pass the Scene and Camera to the Renderer:

renderer.render(scene, camera);

Now you have the foundation for a scene! If you look at your app in the browser you should see an empty canvas element that takes up the entire window, so the next step is to add a 3D shape.

Step 4: Add a 3D Shape to Your Scene

  1. First, add a Geometry, let’s use the DodecahedronGeometry. It has radius and detail properties. Detail refers to extra vertices, which we’ll leave at 0, and we’ll have a radius of 10:
const geometry = new THREE.DodecahedronGeometry(10, 0);

2. Next, instantiate a Material, which will define what the surface of the Geometry will look like. Use MeshBasicMaterial, which is a built in Material that doesn’t require a light source. It takes a property object as an argument, which you can use to give it a color and set wireframe to true in order to see its vertices:

const material = new THREE.MeshBasicMaterial({
color: 0x0096ff,
wireframe: true,
});

3. Pass the Geometry and Material to a newly instantiated Mesh, which creates a 3D shape:

const shape = new THREE.Mesh(geometry, material);

4. Lastly, add the new Mesh to the Scene so it can be rendered:

scene.add(shape);

Step 5: Animate Your Scene

Now that you’ve added something to the Scene, you need to re-render it to see the changes. Instead of re-rendering manually after every change, let’s create an animation loop.

  1. Create and call a recursive function that calls requestAnimationFrame in the browser, which will ‘repaint’ the Scene automatically:
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();

2. Animate the Mesh using its properties. Change the Mesh’s rotation inside of the recursive function along the x, y and z axes:

function animate() {
requestAnimationFrame(animate);
shape.rotation.x += 0.01;
shape.rotation.y += 0.005;
shape.rotation.z += 0.01;
renderer.render(scene, camera);
}
animate()

You should now see a dodecahedron rotating in an infinite loop in your browser! This is a simple animation, but it is enough to gain an understanding of how more complex scenes can be created. You could create more Geometry, Material and Texture objects to create more Meshes that make up complex scenes. You could introduce Light objects to change the atmosphere, or animate objects based on user interactions. The important thing is that you now know what a Mesh even is, and have foundational knowledge to go forth in your web animation journey. The possibilities are endless from this point forward, and there is a thriving three.js community full of tutorials, ideas and assets to help you on your way.

Troubleshooting

Browser Compatibility

Check if your browser is up-to-date or consider using a browser such as Safari, Chrome, Firefox, or Edge if you aren’t already.

Dependency Compatibility

Ensure that you have at least Node.js version 18, and npm version 8. Here is a guide for updating Node.js and npm.

Console Errors

Open your browser’s developer tools (usually by pressing F12 or right-clicking on the page and selecting “Inspect”) and check the console for any error messages.

Typos and Syntax Errors

Carefully review your code for any typos or syntax errors. A linter like ESLint is recommended.

Resources

three.js fundamentals

three.js docs

WebGL docs

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--