genart.dev

Three.js

Three.js renderer — algorithm contract, lifecycle, and ESM import

Three.js Renderer

The Three.js renderer uses Three.js for 3D scenes with WebGL. It provides the full THREE namespace as an ES module import.

Algorithm contract

function sketch(THREE, state, container)
ArgumentTypeDescription
THREEmoduleThree.js namespace (all classes)
stateobjectRuntime state
containerHTMLElementDOM element to mount the renderer into

State object

PropertyTypeDescription
state.canvas.widthnumberCanvas width
state.canvas.heightnumberCanvas height
state.seednumberRandom seed
state.paramsobjectParameter values
state.colorPalettestring[]Hex color array

Required return

return {
  initializeSystem() { /* rebuild scene from state */ },
  dispose() { /* clean up WebGL resources */ },
  pause() { /* stop animation loop */ },
  resume() { /* restart animation loop */ }
};

All four lifecycle methods are required.

Validation

  • Must define function sketch(THREE, state, container) with three arguments

Template

function sketch(THREE, state, container) {
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(
    75, state.canvas.width / state.canvas.height, 0.1, 1000
  );
  const renderer = new THREE.WebGLRenderer({
    antialias: true,
    preserveDrawingBuffer: true
  });
  renderer.setSize(state.canvas.width, state.canvas.height);
  container.appendChild(renderer.domElement);
  camera.position.z = 5;

  let animating = true;
  let animId = null;

  function initializeSystem() {
    while (scene.children.length > 0) scene.remove(scene.children[0]);
    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial({ color: 0x22d3ee });
    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
  }

  function animate() {
    if (!animating) return;
    animId = requestAnimationFrame(animate);
    renderer.render(scene, camera);
  }

  function pause() {
    animating = false;
    if (animId !== null) cancelAnimationFrame(animId);
  }

  function resume() {
    animating = true;
    animate();
  }

  function dispose() {
    pause();
    renderer.dispose();
    container.removeChild(renderer.domElement);
  }

  initializeSystem();
  animate();

  return { initializeSystem, dispose, pause, resume };
}

CDN dependency

LibraryVersionURL
Three.js0.172.0https://cdn.jsdelivr.net/npm/three@0.172.0/build/three.module.min.js

Three.js uses ES module import (not UMD). The rendering iframe loads it via <script type="module"> with import * as THREE.

Renderer configuration

{
  "renderer": {
    "type": "three",
    "version": "0.172.x"
  }
}

Tips

  • Always implement dispose() to clean up WebGL resources and prevent memory leaks
  • Use preserveDrawingBuffer: true for screenshot capture
  • Mount the renderer's domElement into the container argument — don't create your own canvas
  • Scene rebuilds go in initializeSystem(), called when state changes