Capítulo 805 de 859

Chapter 805: Canvas Textures (Manual)

Core Idea

Using a live 2D <canvas> as a texture source (CanvasTexture) to generate dynamic content — most commonly text labels — at runtime instead of loading static image files.

Key Concepts

  • CanvasTexture: wraps a <canvas> element so its pixel contents can be used as a texture.
  • texture.needsUpdate: must be set to true after redrawing the canvas so three.js re-uploads the new pixels.
  • Text-label pattern: draw text with the 2D canvas API, then apply that canvas as a texture on a small plane parented to an object (e.g. a name badge above a character).
  • One canvas per texture vs. shared canvas: use a dedicated canvas per texture when it updates often; share one canvas across multiple rarely-updated textures to save memory.
  • Alternative approaches: billboarding (Sprite) if labels should always face the camera, or HTML overlays if labels should never be occluded by 3D geometry.

Code Examples

function makePerson(x, size, name, color) {
  const canvas = makeLabelCanvas(size, name);
  const texture = new THREE.CanvasTexture(canvas);
  texture.minFilter = THREE.LinearFilter;
  texture.wrapS = THREE.ClampToEdgeWrapping;
  texture.wrapT = THREE.ClampToEdgeWrapping;

  const labelMaterial = new THREE.MeshBasicMaterial({
    map: texture,
    side: THREE.DoubleSide,
    transparent: true,
  });
  // ...attach label mesh to a root Object3D alongside body/head meshes
}
  • What it demonstrates: building a CanvasTexture from a 2D-drawn label and applying it to a plane material.

Key Takeaways

  1. CanvasTexture lets you texture objects with anything the 2D canvas API can draw, including dynamic text.
  2. Set texture.needsUpdate = true whenever the canvas contents change, or three.js won't re-upload them.
  3. Use one canvas per texture for frequently-updated content; share a canvas across textures when updates are rare.
  4. Canvas-texture labels live inside the 3D scene and can be occluded; use billboarding or HTML overlays if that's undesirable.

Connects To

  • Sprite / billboards: the follow-up technique for making labels always face the camera.
  • RenderTarget: the recommended approach if you want three.js itself (not the 2D canvas API) to draw into the texture.
  • OrbitControls: used to move the camera around the labeled scene.