Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 39 ยท Getting Started

Setting Up a Three.js Project

Set up Three.js three ways: an import map with no build step, npm with Vite, and a handy responsive template with OrbitControls and resize handling.

Three.js ships as plain ES modules, so there are three common ways to start. You can use an import map and no tools at all, which is how every live example in this course works. You can install it from npm and bundle it with a tool such as Vite, which is what real projects do. Or you can load a prebuilt script, which is only worth it for quick demos. This lesson shows the first two and ends with a reusable template you can paste into any experiment.

Option 1: an import map and a CDN

An import map tells the browser what a bare module name like "three" means. Put it in your HTML before any module script, and every script can then write import * as THREE from "three".

HTML
<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"
  }
}
</script>

The second entry maps the three/addons/ prefix to the examples/jsm folder, where the official helpers live: camera controls, model loaders, post-processing and more. Always pin the same version for both entries, because the add-ons expect the matching core.

This approach needs no installation, works on any static host, and is easy to share. Its downsides: the browser downloads the whole library (around 700 KB before compression) and you have no tree shaking, so it is best for learning, prototypes and small sites.

Option 2: npm and Vite

For a real project, install Three.js as a dependency and let a bundler remove what you do not use. These commands scaffold a plain JavaScript Vite project (see the Vite tutorial for details):

Terminal
npm create vite@latest my-scene -- --template vanilla
cd my-scene
npm install three
npm run dev

Then in src/main.js:

JavaScript
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

With npm the add-ons are imported from three/addons/..., exactly like with the import map, so code moves between the two setups unchanged. A typical project layout looks like this:

TEXT
my-scene/
  index.html          <- contains <canvas id="scene"> or a container div
  public/
    models/           <- .glb files, served as-is at /models/...
    textures/         <- images
  src/
    main.js           <- creates renderer, scene, camera, loop
    objects/          <- functions that build meshes

Files in public/ are served from the site root, so a model there loads with the URL /models/robot.glb. This is where the Loaders chapter will look for assets.

Which canvas?

new THREE.WebGLRenderer() creates its own canvas that you append to the page. You can instead pass one you already placed in your HTML, which gives you full control of its CSS size:

JavaScript
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });

Use your own canvas when the 3D view is one part of a larger layout, such as a product card. Use the generated one for full-screen experiments.

A template with resize handling

Real pages are resized. When the window changes, two things must be updated together: the renderer's drawing size and the camera's aspect ratio. If you forget the camera, everything looks stretched. This template does both, adds camera controls, and checks that WebGL is available. Drag to orbit, scroll to zoom.

Starter template with OrbitControls

Three details are worth memorizing. setPixelRatio(Math.min(devicePixelRatio, 2)) makes the picture sharp on high-density screens while capping the cost on 3x phones. After changing camera.aspect you must call camera.updateProjectionMatrix(), because the camera caches its matrix. And controls.update() is required each frame when damping is on.

Detecting WebGL support

A tiny fraction of browsers or locked-down machines cannot create a WebGL context. Creating a WebGLRenderer then throws an error. Check before you build the scene, and show a message instead of a blank page.

Safe renderer creation

renderer.capabilities is a handy object that reports limits of the user's GPU, such as the largest texture and the number of texture units. It is useful when you debug something that works on your machine but not on a phone.

Open the browser developer tools (F12) while you work. Three.js prints precise warnings to the console, such as shader compile errors, missing textures and deprecated calls. Most beginner problems are explained there.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an import map let you do?

    The map connects the specifier you import to the real file, so no bundler is needed for simple projects.
  2. 2. After changing camera.aspect on resize, which call must follow?

    The projection matrix is cached. It is only recalculated when you ask for it.
  3. 3. Why cap the pixel ratio with Math.min(devicePixelRatio, 2)?

    A 3x phone screen has nine times the pixels of a 1x screen. Capping at 2 keeps most of the sharpness with a much lighter workload.
  4. 4. Where do you put a model file so Vite serves it at /models/robot.glb?

    Files in public/ are copied untouched and served from the site root.

Summary

  • An import map plus a CDN is the quickest way to run Three.js; npm plus Vite is the way to ship projects.
  • Add-ons (controls, loaders, post-processing) live under three/addons/ and must match the core version.
  • On resize, update both renderer.setSize and the camera aspect, then call updateProjectionMatrix().
  • Cap the pixel ratio and wrap renderer creation in try/catch for robust pages.

Next: Coordinates, Position, Rotation and Scale