Threejs Scene Setup

作者 gamedev-skillsd4b0e35550c5无许可证1.3K 个星标收录于 2026年10月8日更新于 2026年10月8日仓库11天前更新

Stand up a three.js scene: import maps and the three/addons path, the Scene/PerspectiveCamera/WebGLRenderer trio, the setAnimationLoop render loop, responsive resize, and OrbitControls. Use when starting or debugging a three.js app — when the user mentions three.js, THREE.Scene, WebGLRenderer, PerspectiveCamera, the render loop, resizing, or OrbitControls. For models use threejs-gltf-loading; for materials/lights use threejs-materials-lighting.

AI 生成的概览

指导搭建 three.js 场景:导入映射、场景/相机/渲染器、渲染循环、自适应尺寸与 OrbitControls。

功能
提供搭建 three.js 应用的说明与代码示例:通过导入映射以 ES 模块方式加载 three.js,创建 Scene、PerspectiveCamera 与 WebGLRenderer 三件套,添加网格,用 setAnimationLoop 和 Timer 驱动渲染循环,处理自适应尺寸,并添加 OrbitControls。它还列出常见问题,例如模块说明符无法解析、画布全黑、视图拉伸,并指向一份关于场景图的参考文件。它产出的是指导与示例代码,而不是文件或脚本。
适用场景
适用于新建 three.js 应用或调试现有应用时,尤其是画布空白或全黑、画布自适应尺寸、动画循环或 OrbitControls 相关的问题。它不用于加载 glTF 模型、材质与灯光或 2D 渲染,这些由其他技能覆盖。
运行要求
不附带脚本,仅为说明文档。按其中的模式操作需要浏览器中的 JavaScript 运行时,或 Vite、webpack 等打包工具;若通过导入映射从 CDN 加载 three.js,还需要网络访问。

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 r186. 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

  1. 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/....
  2. 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.
  3. Add a mesh. new Mesh(geometry, material) and scene.add(mesh). With a lit material you also need a light (see threejs-materials-lighting).
  4. Drive a render loop with renderer.setAnimationLoop(fn). It's the modern, WebXR-/WebGPU-safe replacement for hand-rolled requestAnimationFrame. Use a Timer for delta time (Clock is deprecated since r183).
  5. Handle resize so the camera aspect and renderer match the canvas; update camera.aspect, call updateProjectionMatrix(), and renderer.setSize(...).
  6. 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)

html
<canvas id="c"></canvas><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><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

js
// main.jsimport * 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 perfrenderer.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 + Timer)

js
const timer = new THREE.Timer();        // replaces the deprecated THREE.Clock (r183+)timer.connect(document);                // optional: no huge delta after a hidden tab
renderer.setAnimationLoop((time) => {  timer.update(time);                   // call once per frame, before getDelta()  const dt = timer.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

js
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)

js
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const controls = new OrbitControls(camera, renderer.domElement);controls.enableDamping = true;          // inertial feelcontrols.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.

来源与署名

来源:gamedev-skills/awesome-gamedev-agent-skills位于skills/web-engines/threejs-scene-setup提交d4b0e35

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架