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)| Argument | Type | Description |
|---|---|---|
THREE | module | Three.js namespace (all classes) |
state | object | Runtime state |
container | HTMLElement | DOM element to mount the renderer into |
State object
| Property | Type | Description |
|---|---|---|
state.canvas.width | number | Canvas width |
state.canvas.height | number | Canvas height |
state.seed | number | Random seed |
state.params | object | Parameter values |
state.colorPalette | string[] | 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
| Library | Version | URL |
|---|---|---|
| Three.js | 0.172.0 | https://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: truefor screenshot capture - Mount the renderer's
domElementinto thecontainerargument — don't create your own canvas - Scene rebuilds go in
initializeSystem(), called when state changes