Examples
Practical examples. Live demos.
Pick an example to open it full screen, with the live preview and its source side by side.
Pick an example to open it full screen, with the live preview and its source side by side.
A library that owns its own state. The panel reads positions, colors and flags straight from the three.js objects and writes edits back to them. The render loop calls update() once per frame; nothing is mirrored.
Loading three.js…
// app.ts: the inspector. There is no state of its own: every value on screen // is read from the three.js object it belongs to, and every control writes // to that object. The render loop calls update() once per frame, after // three.js has moved things, and that is the only update() in this file. import "nuclo"; import type * as THREE from "three"; import { createWorld, type World } from "./scene.ts"; import { s } from "./styles.ts"; let world: World | null = null; let selected: THREE.Mesh | null = null; let status = "Loading three.js…"; const meshes = () => world?.meshes() ?? []; const material = (m: THREE.Mesh) => m.material as THREE.MeshStandardMaterial; const hex = (m: THREE.Mesh) => `#${material(m).color.getHexString()}`; function Stage() { return div( s.stage, canvas( s.canvas, on("mount", (el) => { let stop = () => {}; createWorld(el).then((w) => { if (!el.isConnected) return w.dispose(); // closed before three.js arrived world = w; const box = el.parentElement!; const sizes = new ResizeObserver(() => w.resize(box.clientWidth, box.clientHeight)); sizes.observe(box); const stopLoop = w.start(update); // every frame: sync the panel with the scene stop = () => { stopLoop(); sizes.disconnect(); w.dispose(); world = selected = null; }; }).catch((err: Error) => { status = `three.js did not load: ${err.message}`; update(); }); return () => stop(); }), { onPointerDown: (e) => { selected = world?.pick(e.offsetX, e.offsetY) ?? null; } }, ), when(() => world === null, p(s.loading, () => status)), ); } function Row(mesh: THREE.Mesh) { return li( s.row, { class: () => cx(s.row, mesh === selected ? s.selected : null).className, onClick: () => { selected = mesh; } }, span(s.swatch, { style: () => ({ backgroundColor: hex(mesh) }) }), span(s.name, mesh.name), span(s.coords, () => (mesh.visible ? `y ${mesh.position.y.toFixed(2)} rot ${(mesh.rotation.y % 6.28).toFixed(2)}` : "hidden")), ); } // Only on screen while something is selected, so `selected!` is safe here. function Inspector() { const sel = () => selected!; return div( s.props, h4(s.propsTitle, () => sel().name), label(s.field, span("Color"), input({ type: "color", value: () => hex(sel()) }, { onInput: (e) => { material(sel()).color.set(e.currentTarget.value); } })), label(s.field, span("Scale"), input({ type: "range", min: "0.3", max: "2.5", step: "0.05", value: () => String(sel().scale.x) }, { onInput: (e) => { sel().scale.setScalar(Number(e.currentTarget.value)); } })), label(s.field, span("Spin"), input({ type: "range", min: "-3", max: "3", step: "0.1", value: () => String(sel().userData.spin) }, { onInput: (e) => { sel().userData.spin = Number(e.currentTarget.value); } })), label(s.check, input({ type: "checkbox", checked: () => sel().visible }, { onChange: () => { sel().visible = !sel().visible; } }), "Visible"), label(s.check, input({ type: "checkbox", checked: () => material(sel()).wireframe }, { onChange: () => { material(sel()).wireframe = !material(sel()).wireframe; } }), "Wireframe"), button(s.btn, "Remove", { onClick: () => { world?.remove(sel()); selected = null; } }), ); } export function ThreeInspector() { return div( s.app, Stage(), aside( s.panel, div(s.panelHead, strong("Scene"), span(s.stats, () => `${meshes().length} objects · ${world?.fps ?? 0} fps · ${world?.renderer.info.render.triangles ?? 0} triangles`)), ul(s.list, list(meshes, Row)), when(() => selected !== null, Inspector()).else(p(s.hint, "Click an object, in the scene or in the list.")), button(s.btn, s.primary, "Add object", { onClick: () => { world?.add(); } }), ), ); }
// scene.ts: a plain three.js scene. three.js owns every object in it: the // meshes, their positions, colors, visibility. Nothing here is written for a // UI, and nothing is copied out of it: the inspector reads these objects // where they live, and writes to them directly. import type * as THREE from "three"; // Loaded on demand, so this page costs nothing until the scene mounts. // In an app you would write: import * as THREE from "three". const THREE_URL = "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js"; export interface World { renderer: THREE.WebGLRenderer; fps: number; meshes(): THREE.Mesh[]; add(): THREE.Mesh; remove(mesh: THREE.Mesh): void; pick(x: number, y: number): THREE.Mesh | null; resize(width: number, height: number): void; start(onFrame: () => void): () => void; dispose(): void; } export async function createWorld(canvas: HTMLCanvasElement): Promise<World> { const THREE: typeof import("three") = await import(/* @vite-ignore */ THREE_URL); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100); camera.position.set(0, 3.2, 8.5); camera.lookAt(0, 0, 0); const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); scene.add(new THREE.HemisphereLight(0xffffff, 0x334466, 1.6)); const sun = new THREE.DirectionalLight(0xffffff, 2.2); sun.position.set(4, 6, 5); scene.add(sun); scene.add(new THREE.GridHelper(10, 10, 0x888888, 0x666666)); const shapes = { Box: () => new THREE.BoxGeometry(1.2, 1.2, 1.2), Sphere: () => new THREE.SphereGeometry(0.75, 32, 16), Torus: () => new THREE.TorusGeometry(0.6, 0.25, 16, 48), Cone: () => new THREE.ConeGeometry(0.7, 1.4, 32), Knot: () => new THREE.TorusKnotGeometry(0.5, 0.18, 96, 12), }; const kinds = Object.keys(shapes) as (keyof typeof shapes)[]; let count = 0; const meshes = () => scene.children.filter((o): o is THREE.Mesh => o instanceof THREE.Mesh); // Spread the meshes on a ring, so the scene stays readable as it changes. function layout() { const all = meshes(); all.forEach((m, i) => { const angle = (i / all.length) * Math.PI * 2 - Math.PI / 2; m.position.x = Math.cos(angle) * 3; m.position.z = Math.sin(angle) * 3; }); } function add() { const kind = kinds[count % kinds.length]; const color = new THREE.Color().setHSL((count * 0.17 + 0.05) % 1, 0.7, 0.55); const mesh = new THREE.Mesh(shapes[kind](), new THREE.MeshStandardMaterial({ color, roughness: 0.45 })); mesh.name = `${kind} ${++count}`; mesh.userData.spin = 0.8; // plain data on the object; the inspector edits it scene.add(mesh); layout(); return mesh; } function remove(mesh: THREE.Mesh) { scene.remove(mesh); mesh.geometry.dispose(); (mesh.material as THREE.Material).dispose(); layout(); } const raycaster = new THREE.Raycaster(); const pointer = new THREE.Vector2(); function pick(x: number, y: number) { pointer.set((x / canvas.clientWidth) * 2 - 1, -(y / canvas.clientHeight) * 2 + 1); raycaster.setFromCamera(pointer, camera); const hit = raycaster.intersectObjects(meshes())[0]; return hit ? (hit.object as THREE.Mesh) : null; } function resize(width: number, height: number) { renderer.setSize(width, height, false); camera.aspect = width / height; camera.updateProjectionMatrix(); } const world: World = { renderer, fps: 0, meshes, add, remove, pick, resize, start(onFrame) { let last = performance.now(); let frame = requestAnimationFrame(function loop(now) { const dt = Math.min((now - last) / 1000, 0.1); last = now; world.fps = Math.round(world.fps * 0.9 + (1 / dt) * 0.1); meshes().forEach((m, i) => { m.rotation.y += m.userData.spin * dt; m.position.y = Math.sin(now / 900 + i) * 0.3; }); renderer.render(scene, camera); onFrame(); frame = requestAnimationFrame(loop); }); return () => cancelAnimationFrame(frame); }, dispose() { lut.dispose(); renderer.dispose(); }, }; for (let i = 0; i < 5; i++) add(); // three.js shares one lookup texture (DFG_LUT) between every renderer, and // that texture keeps each renderer that drew with it reachable, canvas and // page included, until it is disposed. Render once to get hold of it. renderer.render(scene, camera); const lut = (renderer.properties.get(meshes()[0].material) as { uniforms: { dfgLUT: { value: THREE.Texture } } }).uniforms.dfgLUT.value; return world; }
import "nuclo"; const mono = "ui-monospace, monospace"; const control = { height: "34px", padding: "0 12px", borderRadius: "8px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontFamily: "inherit", fontSize: "0.875rem", fontWeight: "600" }; export const s = { app: css("three-app", { display: "flex", flexDirection: "column", gap: "12px", width: "100%", height: "100%", "@media (min-width: 900px)": { flexDirection: "row" } }), stage: css("three-stage", { position: "relative", flex: "1", minWidth: "0", minHeight: "260px", borderRadius: "12px", border: "1px solid var(--c-border)", overflow: "hidden", backgroundColor: "var(--c-bg-secondary)" }), canvas: css("three-canvas", { display: "block", width: "100%", height: "100%", cursor: "crosshair", touchAction: "none" }), loading: css("three-loading", { position: "absolute", inset: "0", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "0.875rem", color: "var(--c-text-muted)" }), panel: css("three-panel", { display: "flex", flexDirection: "column", gap: "10px", flexShrink: 0, width: "100%", overflowY: "auto", "@media (min-width: 900px)": { width: "300px" } }), panelHead: css("three-panelHead", { display: "flex", flexDirection: "column", gap: "2px", fontSize: "0.9375rem" }), stats: css("three-stats", { fontFamily: mono, fontSize: "0.75rem", color: "var(--c-text-muted)", fontVariantNumeric: "tabular-nums" }), list: css("three-list", { listStyle: "none", borderRadius: "10px", border: "1px solid var(--c-border)", overflow: "hidden", "& > * + *": { raw: { "border-top": "1px solid var(--c-border)" } } }), row: css("three-row", { display: "flex", alignItems: "center", gap: "8px", height: "36px", padding: "0 10px", fontSize: "0.8125rem", cursor: "pointer", hover: { backgroundColor: "var(--c-bg-secondary)" } }), selected: css("three-selected", { backgroundColor: "var(--c-primary-alpha-13)", hover: { backgroundColor: "var(--c-primary-alpha-13)" } }), swatch: css("three-swatch", { width: "12px", height: "12px", borderRadius: "4px", flexShrink: 0 }), name: css("three-name", { flex: "1", fontWeight: "500" }), coords: css("three-coords", { fontFamily: mono, fontSize: "0.6875rem", color: "var(--c-text-muted)", whiteSpace: "pre", fontVariantNumeric: "tabular-nums" }), hint: css("three-hint", { fontSize: "0.8125rem", color: "var(--c-text-dim)" }), props: css("three-props", { display: "flex", flexDirection: "column", gap: "8px", padding: "12px", borderRadius: "10px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-card)" }), propsTitle: css("three-propsTitle", { fontSize: "0.875rem", fontWeight: "600" }), field: css("three-field", { display: "grid", gridTemplateColumns: "52px 1fr", alignItems: "center", gap: "8px", fontSize: "0.8125rem", color: "var(--c-text-dim)", "& input": { width: "100%", accentColor: "var(--c-primary)" }, "& input[type=color]": { height: "28px", padding: "0", border: "none", backgroundColor: "transparent", cursor: "pointer" } }), check: css("three-check", { display: "flex", alignItems: "center", gap: "8px", fontSize: "0.8125rem", color: "var(--c-text-dim)", cursor: "pointer", "& input": { accentColor: "var(--c-primary)" } }), btn: css("three-btn", { ...control, hover: { backgroundColor: "var(--c-bg-secondary)" } }), primary: css("three-primary", { backgroundColor: "var(--c-primary-dark)", borderColor: "transparent", color: "#fff", hover: { backgroundColor: "var(--c-primary-dark)", filter: "brightness(0.92)" } }), };