Capítulo 808 de 859

Chapter 808: Creating a Scene (Manual)

Core Idea

The canonical three.js "hello world": a Scene, a PerspectiveCamera, and a WebGLRenderer, with a rotating cube driven by an animation loop.

Key Concepts

  • Scene: the container objects, lights and cameras get added to.
  • PerspectiveCamera(fov, aspect, near, far): fov in degrees, aspect normally element-width/height, near/far the clipping distances.
  • WebGLRenderer + setSize: creates the renderer and sizes its output to match the display area.
  • Mesh = Geometry + Material: e.g. BoxGeometry (the cube's vertices/faces) plus MeshBasicMaterial (an unlit color) combined via Mesh.
  • Default position: scene.add() places new objects at the origin, so either the camera or the object needs to move to avoid starting inside each other.
  • renderer.setAnimationLoop: the per-frame callback that drives rendering, built on requestAnimationFrame so it automatically pauses on background tabs.

Code Examples

import * as THREE from "three";

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

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animate);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate(time) {
  cube.rotation.x = time / 2000;
  cube.rotation.y = time / 1000;
  renderer.render(scene, camera);
}
  • What it demonstrates: the minimal setup for a three.js app — scene, camera, renderer, one mesh, and an animation loop.

Key Takeaways

  1. Every three.js app needs at minimum a Scene, a Camera, and a Renderer.
  2. A Mesh is a Geometry (shape data) combined with a Material (surface appearance).
  3. New objects default to the origin, so move the camera (or the object) back to avoid them starting inside each other.
  4. Use renderer.setAnimationLoop rather than a manual setInterval/requestAnimationFrame loop — it handles pausing on inactive tabs for you.

Connects To

  • PerspectiveCamera: the camera type used here; see its reference chapter for the full constructor/property list.
  • BoxGeometry / MeshBasicMaterial: the geometry/material pair forming the cube.
  • WebGLRenderer: renders the scene and owns the animation loop.