Computing

Three.js: 3D in the browser


What is Three.js?

Three.js is a JavaScript library that makes it easier to display 3D in the browser. It’s built on WebGL (and WebGPU) and saves you from writing shaders and handling low-level details yourself.

The three basic building blocks

Every Three.js project relies on three elements:

  • a scene (Scene) that holds the objects and lights;
  • a camera (PerspectiveCamera) that defines the point of view;
  • a renderer (WebGLRenderer) that draws the scene in a <canvas>.

A visible object (Mesh) combines a geometry (the shape) and a material (the look).

Minimal example

import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(50, 1, 0.1, 100);
camera.position.z = 5;

const mesh = new THREE.Mesh(
	new THREE.TorusKnotGeometry(1, 0.32, 160, 24),
	new THREE.MeshStandardMaterial({ color: 0x7c8cff }),
);
scene.add(mesh, new THREE.DirectionalLight(0xffffff, 2));

function render() {
	requestAnimationFrame(render);
	mesh.rotation.y += 0.01;
	renderer.render(scene, camera);
}
render();

The demo

Here’s the result: a rotating torus knot. The button lets you switch to wireframe mode to see the mesh.

With Astro

Three.js is heavy: to keep the site fast, load it with a dynamic import(), only when the canvas is visible. That’s what this demo does.

Key takeaways

With a scene, a camera and a renderer, you get 3D in just a few lines. To go further: lights, textures, glTF models and camera controls (OrbitControls).