three.js Scene Setup
Create the foundation of a three.js app: module loading, the
scene/camera/renderer trio, the render loop, responsive resizing, and camera
controls. Patterns target r184. Read the installed three version before
changing an existing project because examples and addons move across releases.
When to use
- Use when bootstrapping a three.js scene, fixing a blank/black canvas, making the
canvas responsive, setting up the animation loop, or adding
OrbitControls.
- Use when
package.json depends on three and code does import * as THREE from 'three'.
When not to use: loading .gltf/.glb models or skinned animation →
threejs-gltf-loading. Materials, lights, shadows, environment maps →
threejs-materials-lighting. 2D rendering → pixijs-rendering.
Core workflow
- Load three.js as an ES module with an import map. Since r147 the bare
specifier
'three' and 'three/addons/' must be mapped (in HTML or by a
bundler). Addons (controls, loaders) live under three/addons/....
- Create the trio. A
Scene (root of the graph), a PerspectiveCamera(fov, aspect, near, far) moved back from the origin, and a WebGLRenderer whose
domElement is in the DOM. Set size and pixelRatio.
- Add a mesh.
new Mesh(geometry, material) and scene.add(mesh). With a
lit material you also need a light (see threejs-materials-lighting).
- Drive a render loop with
renderer.setAnimationLoop(fn). It's the modern,
WebXR-/WebGPU-safe replacement for hand-rolled requestAnimationFrame. Use a
Clock for delta time.
- Handle resize so the camera aspect and renderer match the canvas; update
camera.aspect, call updateProjectionMatrix(), and renderer.setSize(...).
- Add
OrbitControls for orbit/pan/zoom while developing. Confirm something
actually renders (a lit cube, the controls responding) before assuming success.
Patterns
1. HTML import map + module entry (no bundler)
<canvas id="c"></canvas>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.184.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.184.0/examples/jsm/"
}
}
</script>
<script type="module" src="./main.js"></script>
With a bundler (Vite/webpack), skip the import map and just
npm i three; the same import statements resolve.
2. Scene + camera + renderer
// main.js
import * as THREE from 'three';
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // cap for perf
renderer.setSize(window.innerWidth, window.innerHeight);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101018);
const camera = new THREE.PerspectiveCamera(
60, // vertical field of view (degrees)
window.innerWidth / window.innerHeight, // aspect
0.1, // near
100 // far
);
camera.position.set(3, 2, 5);
camera.lookAt(0, 0, 0);
const cube = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshNormalMaterial() // unlit; shows orientation without a light
);
scene.add(cube);
3. The render loop (setAnimationLoop + Clock)
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const dt = clock.getDelta(); // seconds since last frame
cube.rotation.x += dt; // frame-rate independent
cube.rotation.y += dt * 0.7;
renderer.render(scene, camera);
});
// renderer.setAnimationLoop(null); // stop the loop
4. Responsive resize
function onResize() {
const w = window.innerWidth, h = window.innerHeight;
camera.aspect = w / h;
camera.updateProjectionMatrix(); // required after changing aspect
renderer.setSize(w, h);
}
window.addEventListener('resize', onResize);
5. OrbitControls (orbit / pan / zoom)
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // inertial feel
controls.target.set(0, 0, 0);
renderer.setAnimationLoop(() => {
controls.update(); // needed every frame when damping is on
renderer.render(scene, camera);
});
Pitfalls
Failed to resolve module specifier "three" → missing import map (or bundler
config). Map both "three" and "three/addons/"; addon paths must end with /.
- Black canvas, no errors → camera is at the origin (inside/behind the object),
or you used a lit material (
MeshStandardMaterial) with no light. Move the camera
back; use MeshNormalMaterial/MeshBasicMaterial to verify geometry first.
- Nothing animates → you never called
renderer.render inside the loop, or you
call setAnimationLoop but render outside it.
- Stretched / squashed view on resize → you resized the renderer but didn't
update
camera.aspect + updateProjectionMatrix().
- Blurry or jagged on HiDPI → set
renderer.setPixelRatio(...); cap it (≈2) so
4K/retina screens don't tank performance.
- OrbitControls feel dead → with
enableDamping = true you must call
controls.update() every frame.
- Old tutorials use
<script src="three.min.js"> → since r147 three.js ships
ES modules only; use type="module" + import maps.
References
- For coordinate conventions, the scene-graph (
Group, parent/child transforms,
Object3D add/remove), OrthographicCamera for 2.5D, and disposing of
geometries/materials/textures to avoid leaks, read references/scene-graph.md.
Related skills
threejs-materials-lighting — give surfaces a lit look (lights, shadows, PBR).
threejs-gltf-loading — load 3D models and play their animations.
pixijs-rendering — 2D rendering in the browser.
fps-shooter — a 3D genre template that composes three.js skills.
1---
2name: threejs-scene-setup
3description: >
4 Stand up a three.js scene: import maps and the three/addons path, the
5 Scene/PerspectiveCamera/WebGLRenderer trio, the setAnimationLoop render loop,
6 responsive resize, and OrbitControls. Use when starting or debugging a three.js
7 app — when the user mentions three.js, THREE.Scene, WebGLRenderer,
8 PerspectiveCamera, the render loop, resizing, or OrbitControls. For models use
9 threejs-gltf-loading; for materials/lights use threejs-materials-lighting.
10---
11
12# three.js Scene Setup
13
14Create the foundation of a three.js app: module loading, the
15scene/camera/renderer trio, the render loop, responsive resizing, and camera
16controls. Patterns target **r184**. Read the installed `three` version before
17changing an existing project because examples and addons move across releases.
18
19## When to use
20
21- Use when bootstrapping a three.js scene, fixing a blank/black canvas, making the
22 canvas responsive, setting up the animation loop, or adding `OrbitControls`.
23- Use when `package.json` depends on `three` and code does `import * as THREE from
24 'three'`.
25
26**When *not* to use:** loading `.gltf`/`.glb` models or skinned animation →
27`threejs-gltf-loading`. Materials, lights, shadows, environment maps →
28`threejs-materials-lighting`. 2D rendering → `pixijs-rendering`.
29
30## Core workflow
31
321. **Load three.js as an ES module with an import map.** Since r147 the bare
33 specifier `'three'` and `'three/addons/'` must be mapped (in HTML or by a
34 bundler). Addons (controls, loaders) live under `three/addons/...`.
352. **Create the trio.** A `Scene` (root of the graph), a `PerspectiveCamera(fov,
36 aspect, near, far)` moved back from the origin, and a `WebGLRenderer` whose
37 `domElement` is in the DOM. Set size and `pixelRatio`.
383. **Add a mesh.** `new Mesh(geometry, material)` and `scene.add(mesh)`. With a
39 lit material you also need a light (see `threejs-materials-lighting`).
404. **Drive a render loop with `renderer.setAnimationLoop(fn)`.** It's the modern,
41 WebXR-/WebGPU-safe replacement for hand-rolled `requestAnimationFrame`. Use a
42 `Clock` for delta time.
435. **Handle resize** so the camera aspect and renderer match the canvas; update
44 `camera.aspect`, call `updateProjectionMatrix()`, and `renderer.setSize(...)`.
456. **Add `OrbitControls`** for orbit/pan/zoom while developing. Confirm something
46 actually renders (a lit cube, the controls responding) before assuming success.
47
48## Patterns
49
50### 1. HTML import map + module entry (no bundler)
51
52```html
53<canvas id="c"></canvas>
54<script type="importmap">
55{
56 "imports": {
57 "three": "https://cdn.jsdelivr.net/npm/three@0.184.0/build/three.module.js",
58 "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.184.0/examples/jsm/"
59 }
60}
61</script>
62<script type="module" src="./main.js"></script>
63```
64
65With a bundler (Vite/webpack), skip the import map and just
66`npm i three`; the same `import` statements resolve.
67
68### 2. Scene + camera + renderer
69
70```js
71// main.js
72import * as THREE from 'three';
73
74const canvas = document.querySelector('#c');
75const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
76renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // cap for perf
77renderer.setSize(window.innerWidth, window.innerHeight);
78
79const scene = new THREE.Scene();
80scene.background = new THREE.Color(0x101018);
81
82const camera = new THREE.PerspectiveCamera(
83 60, // vertical field of view (degrees)
84 window.innerWidth / window.innerHeight, // aspect
85 0.1, // near
86 100 // far
87);
88camera.position.set(3, 2, 5);
89camera.lookAt(0, 0, 0);
90
91const cube = new THREE.Mesh(
92 new THREE.BoxGeometry(1, 1, 1),
93 new THREE.MeshNormalMaterial() // unlit; shows orientation without a light
94);
95scene.add(cube);
96```
97
98### 3. The render loop (setAnimationLoop + Clock)
99
100```js
101const clock = new THREE.Clock();
102
103renderer.setAnimationLoop(() => {
104 const dt = clock.getDelta(); // seconds since last frame
105 cube.rotation.x += dt; // frame-rate independent
106 cube.rotation.y += dt * 0.7;
107 renderer.render(scene, camera);
108});
109// renderer.setAnimationLoop(null); // stop the loop
110```
111
112### 4. Responsive resize
113
114```js
115function onResize() {
116 const w = window.innerWidth, h = window.innerHeight;
117 camera.aspect = w / h;
118 camera.updateProjectionMatrix(); // required after changing aspect
119 renderer.setSize(w, h);
120}
121window.addEventListener('resize', onResize);
122```
123
124### 5. OrbitControls (orbit / pan / zoom)
125
126```js
127import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
128
129const controls = new OrbitControls(camera, renderer.domElement);
130controls.enableDamping = true; // inertial feel
131controls.target.set(0, 0, 0);
132
133renderer.setAnimationLoop(() => {
134 controls.update(); // needed every frame when damping is on
135 renderer.render(scene, camera);
136});
137```
138
139## Pitfalls
140
141- **`Failed to resolve module specifier "three"`** → missing import map (or bundler
142 config). Map both `"three"` and `"three/addons/"`; addon paths must end with `/`.
143- **Black canvas, no errors** → camera is at the origin (inside/behind the object),
144 or you used a lit material (`MeshStandardMaterial`) with no light. Move the camera
145 back; use `MeshNormalMaterial`/`MeshBasicMaterial` to verify geometry first.
146- **Nothing animates** → you never called `renderer.render` inside the loop, or you
147 call `setAnimationLoop` but render outside it.
148- **Stretched / squashed view on resize** → you resized the renderer but didn't
149 update `camera.aspect` + `updateProjectionMatrix()`.
150- **Blurry or jagged on HiDPI** → set `renderer.setPixelRatio(...)`; cap it (≈2) so
151 4K/retina screens don't tank performance.
152- **OrbitControls feel dead** → with `enableDamping = true` you must call
153 `controls.update()` every frame.
154- **Old tutorials use `<script src="three.min.js">`** → since r147 three.js ships
155 ES modules only; use `type="module"` + import maps.
156
157## References
158
159- For coordinate conventions, the scene-graph (`Group`, parent/child transforms,
160 `Object3D` add/remove), `OrthographicCamera` for 2.5D, and disposing of
161 geometries/materials/textures to avoid leaks, read `references/scene-graph.md`.
162
163## Related skills
164
165- `threejs-materials-lighting` — give surfaces a lit look (lights, shadows, PBR).
166- `threejs-gltf-loading` — load 3D models and play their animations.
167- `pixijs-rendering` — 2D rendering in the browser.
168- `fps-shooter` — a 3D genre template that composes three.js skills.