Tools
Tools add interaction and overlays to a scene: camera controls, dragging, hover effects, selection outlines, sculpting, an FPS counter. Add one with scene.use(tool).
import {
OrbitCamera, FlyCamera, DragObject, HoverHighlight, FpsMeter,
} from "./trid/tools/index.js";
scene.use(new OrbitCamera()); // camera tools first
scene.use(new DragObject()); // object tools after, so they get clicks first
scene.use(new HoverHighlight());
scene.use(new FpsMeter());How tools share the mouse
The scene owns the canvas's mouse, touch and scroll listeners and passes events on to its tools. Tools are stacked like layers:
- The last tool added gets the first chance at a click or a scroll.
- The first tool that accepts a click gets the whole drag, until the button is released.
- While nothing is being dragged, every tool sees pointer moves (for hover effects).
That's why the order above works: clicking an object starts a DragObject drag, and clicking empty space falls through to OrbitCamera.
TIP
Use one camera tool at a time. Two tools moving the same camera will fight over it.
OrbitCamera
Turns the camera around a target point. It starts from wherever the camera currently is.
| Input | Action |
|---|---|
| Left drag | Orbit around the target |
| Right drag, middle drag, or Shift + left drag | Pan (moves the target with the cursor) |
| Scroll | Zoom in and out |
| Option | Default | Meaning |
|---|---|---|
target | { x: 0, y: 0, z: 0 } | Point to orbit around |
distance | camera's distance to target | Starting distance |
yaw, pitch | camera's yaw / pitch | Starting angles |
rotateSpeed | 0.005 | Radians per dragged pixel |
zoomSpeed | 0.001 | Zoom amount per scroll unit |
minDistance | 0.1 | Closest zoom |
maxDistance | 100 | Farthest zoom |
rotate, pan, zoom | true | Turn each control off with false |
autoRotate | false | Turn around the target on its own (paused while dragging) |
autoRotateSpeed | 0.5 | Radians per second; negative turns the other way |
autoRotateDelay | 0 | Seconds to wait after a drag before turning again |
target, distance, yaw, pitch and the autoRotate options are public properties you can change at any time. Pitch is kept just under ±90° so the view never flips.
WARNING
OrbitCamera places the camera every frame. To move the view in code, change the tool's properties (e.g. orbit.yaw += dt), not scene.camera — direct camera changes are overwritten.
import { Scene, makeShape, gridHelper, OrbitCamera } from "./trid/index.js";
export default function (canvas) {
const scene = new Scene(canvas, { width: 800, height: 320, camera: { z: -2, fov: 0.7 } });
scene.add(gridHelper({ size: 4, divisions: 20 }));
scene.add({ mesh: makeShape("torus", { R: 0.35, tube: 0.13 }), pos: { x: 0, y: 0.15, z: 0 }, rot: { x: 1.1, y: 0, z: 0.3 }, material: { fill: "#8ab4f8", smooth: true } });
// Spins slowly on its own, and waits 2 s after each drag before spinning again
scene.use(new OrbitCamera({
pitch: -0.3, minDistance: 0.8, maxDistance: 5,
autoRotate: true, autoRotateSpeed: 0.3, autoRotateDelay: 2,
}));
scene.start();
return () => scene.destroy();
}FlyCamera
A free-flying camera driven by the keyboard and mouse.
| Input | Action |
|---|---|
| W / S | Forward / back |
| A / D | Left / right |
| E / Q | Up / down |
| Arrow keys | Turn |
| Left drag | Look around |
| Hold Shift | Move faster |
Keys use physical positions (KeyboardEvent.code), so on an AZERTY keyboard the same keys are Z Q S D. Keys are ignored while typing in an input.
| Option | Default | Meaning |
|---|---|---|
speed | 1 | Units per second |
fastMultiplier | 3 | Speed multiplier while Shift is held |
turnSpeed | 1.5 | Radians per second with the arrow keys |
lookSpeed | 0.005 | Radians per dragged pixel |
TIP
FlyCamera listens to the keyboard on the whole window and stops the arrow keys from scrolling the page. On a page with other content, add it only while the canvas is in use — the demo below does exactly that.
import { Scene, makeShape, gridHelper, FlyCamera } from "./trid/index.js";
export default function (canvas) {
const scene = new Scene(canvas, { width: 800, height: 320, camera: { y: 0.5, z: -2, pitch: -0.15 } });
// A field of blocks on a floor grid, to fly through
scene.add(gridHelper({ size: 14, divisions: 28 }));
const block = makeShape("cube", { size: 0.3 });
for (let x = -3; x <= 3; x++) {
for (let z = 0; z <= 6; z++) {
scene.add({ mesh: block, pos: { x, y: 0.15, z }, material: { fill: `hsl(${(x + z) * 25}, 70%, 65%)` } });
}
}
// Only take the keyboard while the canvas is being used
const fly = new FlyCamera({ speed: 2, lookSpeed: 0 });
const release = (e) => {
if (e.target !== canvas) scene.unuse(fly);
};
canvas.addEventListener("pointerdown", () => scene.use(fly));
document.addEventListener("pointerdown", release);
scene.start();
return () => {
document.removeEventListener("pointerdown", release);
scene.destroy();
};
}DragObject
Click an object to pick it, then drag to move it. The object follows the cursor exactly, parallel to the screen. Hold Shift while dragging to push it away (drag up) or pull it closer (drag down).
| Option | Default | Meaning |
|---|---|---|
button | 0 | Mouse button that drags (0 left, 1 middle, 2 right) |
filter | objects without draggable: false | (obj) => boolean: which objects can be dragged |
exact | false | Pick by triangles instead of bounding boxes (see pickHit) |
root | false | Drag the whole group of the part clicked (its top-level object) |
onPick | — | (obj) => void: called when an object is picked |
onMove | — | (obj) => void: called each time it moves |
onDrop | — | (obj) => void: called when it's released |
tool.dragging is the object being dragged, or null. Objects are found with pick: by screen-space bounding box, or by their triangles with exact: true.
HoverHighlight
Recolors the object under the pointer, and puts its own color back when the pointer leaves it, leaves the canvas, or the tool is removed. Filled objects get their fill recolored too; their material is swapped for a copy, so objects sharing it don't change.
| Option | Default | Meaning |
|---|---|---|
color | "#ffffff" | Highlight color |
filter | objects without hoverable: false | (obj) => boolean: which objects can be highlighted |
exact | false | Pick by triangles instead of bounding boxes (see pickHit) |
onChange | — | (obj) => void: called when the hovered object changes (obj is null when nothing is hovered) |
tool.hovered is the object under the pointer, or null.
FpsMeter
Draws the frames per second in a corner of the canvas. The value is averaged and refreshed every interval seconds so it stays readable.
| Option | Default | Meaning |
|---|---|---|
color | "#ffffff" | Text color |
font | "14px monospace" | CSS font |
corner | "top-left" | "top-left", "top-right", "bottom-left" or "bottom-right" |
interval | 0.5 | Seconds between refreshes |
tool.fps holds the last reading. It only counts while the scene is running.
ObjUploader
Loads .obj files dropped on the canvas, or picked with tool.open(). See Loading OBJ files.
ViewGizmo
The X, Y and Z axes in a corner of the canvas, turning with the camera, like Blender's navigation gizmo. Axes pointing away from you are dimmed; the dots without a letter are the negative ends. Click an axis and the OrbitCamera turns smoothly to look along it.
scene.use(new OrbitCamera());
const gizmo = scene.use(new ViewGizmo({ corner: "top-right" })); // after the camera
gizmo.lookAlong({ x: 0, y: 1, z: 0 }); // look down from above, from code| Option | Default | Meaning |
|---|---|---|
orbit | the scene's first OrbitCamera | Camera controls to turn. Without one, the gizmo only shows the axes |
corner | "top-right" | "top-right", "top-left", "bottom-right" or "bottom-left" |
size | 42 | Radius in CSS pixels |
margin | 14 | Distance from the corner in CSS pixels: a number, or { x, y } |
duration | 0.35 | Seconds the camera takes to turn |
Set gizmo.visible = false to hide it without removing it. gizmo.contains(x, y) tells whether a canvas pixel is on it. While it turns the camera, auto-rotate waits (see autoRotateDelay).
TransformGizmo
Handles to move, rotate and scale objects with the mouse. It works on one or more targets at once, around a pivot: by default their shared center (the middle of their bounding box).
import { Scene, makeShape, gridHelper, OrbitCamera, ViewGizmo, TransformGizmo, pick } from "./trid/index.js";
const MODES = ["move", "rotate", "scale"];
export default function (canvas) {
const scene = new Scene(canvas, {
width: 800, height: 380, camera: { fov: 0.6 }, lineWidth: 1,
});
const shapes = [
scene.add({ mesh: makeShape("cube", { size: 0.4, radius: 0.04, segments: 2 }), pos: { x: -0.7, y: 0, z: 0 }, material: { fill: "#E9806E", smooth: true } }),
scene.add({ mesh: makeShape("torus", { R: 0.22, tube: 0.07 }), pos: { x: 0, y: 0, z: 0 }, material: { fill: "#e5c07b", smooth: true } }),
scene.add({ mesh: makeShape("cone", { r: 0.2, h: 0.45 }), pos: { x: 0.7, y: 0, z: 0 }, material: { fill: "#7ae96e", smooth: true } }),
];
scene.add({ ...gridHelper({ size: 2.4, divisions: 12 }), pos: { x: 0, y: -0.3, z: 0 } });
scene.use(new OrbitCamera({ pitch: -0.35, distance: 2 }));
// Added after the camera, so they get clicks first
scene.use(new ViewGizmo());
const gizmo = scene.use(new TransformGizmo({ targets: [shapes[1]], outline: true }));
// A click (not a drag) selects the shape under it, by its triangles: the torus's hole is empty
let down = null;
const toCanvas = (e) => ({
x: (e.offsetX * canvas.width) / canvas.clientWidth,
y: (e.offsetY * canvas.height) / canvas.clientHeight,
});
canvas.addEventListener("pointerdown", (e) => (down = toCanvas(e)));
canvas.addEventListener("pointerup", (e) => {
const p = toCanvas(e);
if (!down || gizmo.dragging || Math.hypot(p.x - down.x, p.y - down.y) > 4) return;
const hit = pick(scene, p.x, p.y, { exact: true, filter: (o) => shapes.includes(o) });
gizmo.targets = hit ? [hit] : [];
});
// 1 / 2 / 3 switch the mode while the pointer is over the canvas
let over = false;
canvas.addEventListener("pointerenter", () => (over = true));
canvas.addEventListener("pointerleave", () => (over = false));
const onKey = (e) => {
const mode = MODES[Number(e.key) - 1];
if (over && mode) gizmo.mode = mode;
};
addEventListener("keydown", onKey);
scene.start();
return () => {
removeEventListener("keydown", onKey);
scene.destroy();
};
}| Mode | Handles | Drag |
|---|---|---|
"move" | X, Y, Z arrows | Moves along that world axis |
"rotate" | X, Y, Z rings | Turns around that axis. The ring follows the mouse from any angle; where rings cross, the one facing you wins |
"scale" | X, Y, Z handles with square ends, and a center square | Stretches along that axis; the center square scales evenly (×2 per 100 px dragged right, smaller to the left) |
| Option | Default | Meaning |
|---|---|---|
mode | "move" | "move", "rotate" or "scale"; change gizmo.mode at any time |
targets | [] | Objects it edits; change gizmo.targets at any time. No targets: no handles |
size | 70 | Handle length in CSS pixels (the same on screen at any distance) |
apply | true | Change the targets' pos, rot and scale while dragging |
pivot | "bounds" | Where the handles sit and what rotate and scale go around. See Pivot |
onGrab | — | (targets) => void: a handle was grabbed |
onChange | — | (op, targets) => void: while dragging, the operation since the grab |
onDrop | — | (op, targets) => void: on release, the whole operation |
outline | false | Outline the targets, under the handles: true, or SelectionOutline options like { color: "#ffffff" } |
gizmo.dragging is true while a handle is held, and gizmo.visible = false hides it. Clicks that miss the handles fall through to the tools below (the camera), so add the gizmo after the camera tool.
Pivot
pivot (an option, or gizmo.pivot at any time) sets where the handles sit. Rotate and scale go around it: it's the center of the operations.
pivot | Where |
|---|---|
"bounds" | The middle of the targets' bounding box (the default) |
"origin" | The targets' origins in the world (their pos, with their groups), averaged for several targets |
{ x, y, z } | A point in the world. When the gizmo moves the targets, it moves this point with them, so the handles stay on it |
(targets) => point | Asked every frame: for a pivot your app keeps in its own data (return null for no handles) |
gizmo.pivot = "origin"; // turn around the object's own origin
gizmo.pivot = { x: 0, y: 0, z: 0 }; // around the world's center
gizmo.pivot = ([part]) => worldPivotOf(part); // from your datagizmo.center() returns the pivot in world space.
Applying the changes yourself
Stretching a rotated object along a world axis can't be stored as scale (that would shear it), so the gizmo stretches the object's own axis that points most along it. A rotation turns both the position (around the center) and rot.
With apply: false, the gizmo changes nothing and only reports operations, so an app can apply them to its own data (an undo stack, a model made of parts, a server). Each operation is relative to the grab, so apply it to the transform you saved in onGrab:
let saved = [];
const gizmo = scene.use(new TransformGizmo({
apply: false,
onGrab: (targets) => (saved = targets.map((t) => ({ pos: { ...t.pos }, rot: { ...t.rot }, scale: { ...t.scale } }))),
onChange: (op, targets) => targets.forEach((t, i) => Object.assign(t, applyTransformOp(saved[i], op))),
onDrop: (op) => history.push(op),
}));An operation is one of:
{ mode: "move", delta } // a world-space vector
{ mode: "rotate", axis, angle, center } // right-handed, radians, around the unit axis
{ mode: "scale", axis, factor, center } // axis null: uniformSelectionOutline
A colored line around the selected objects, like a 3D editor's selection. Where something in front hides part of them, that part's outline is drawn faintly, so you still see where the whole selection is. A group is outlined as one shape.
const selection = scene.use(new SelectionOutline());
selection.targets = [chair]; // change at any time; [] outlines nothingThe gizmo demo above uses it through TransformGizmo({ outline: true }): whatever the gizmo moves is outlined. Turn the view so the torus goes behind another shape to see the faint part.
| Option | Default | Meaning |
|---|---|---|
targets | [] | Objects to outline, or a function asked every frame, like () => gizmo.targets |
color | "#ffa64d" | Line color |
width | 2 | Line width in CSS pixels |
hidden | 0.35 | Opacity of the outline where the objects are hidden behind others. 0 doesn't show it |
selection.visible = false hides it. It draws on the finished picture, after post effects, so it looks the same with both renderers. Add it before tools with handles (like TransformGizmo), so the handles stay on top: tools draw in the order they were added.
For outlines on every object as a drawing style, see the outline() post effect instead.
SculptTool
Sculpt meshes with the mouse, like Blender's sculpt mode: drag on a mesh to paint a sculpting brush onto it. A circle shows the brush under the cursor.
import { Scene, makeShape, SculptTool, SCULPT_BRUSHES, WebGLRenderer, OrbitCamera } from "./trid/index.js";
export default function (canvas) {
const scene = new Scene(canvas, {
width: 800, height: 400, camera: { fov: 0.6 },
renderer: WebGLRenderer.isSupported() ? new WebGLRenderer() : undefined,
});
// A dense ball to sculpt
scene.add({ mesh: makeShape("sphere", { r: 0.5, rings: 64, segments: 128 }), material: { fill: "#E9806E", smooth: true } });
scene.use(new OrbitCamera({ distance: 3, pitch: -0.2 })); // drag off the ball to turn around it
const sculpt = scene.use(new SculptTool({ brush: "inflate", radius: 35, symmetry: "x" }));
// A row of brush names to click, drawn on the canvas (added last, so it gets clicks first)
const items = [...SCULPT_BRUSHES, "mirror x"];
const box = (i) => ({ x: 12 + i * 92, y: 12, w: 86, h: 26 });
scene.use({
pointerDown(e) {
const i = items.findIndex((_, k) => {
const b = box(k);
return e.x >= b.x && e.x <= b.x + b.w && e.y >= b.y && e.y <= b.y + b.h;
});
if (i < 0) return false;
if (items[i] === "mirror x") sculpt.symmetry = sculpt.symmetry ? undefined : "x";
else sculpt.brush = items[i];
return true;
},
draw(ctx) {
ctx.save();
ctx.font = "13px system-ui, sans-serif";
ctx.textBaseline = "middle";
items.forEach((name, i) => {
const b = box(i);
const on = name === "mirror x" ? !!sculpt.symmetry : sculpt.brush === name;
ctx.fillStyle = on ? "#E9806E" : "rgba(255,255,255,0.12)";
ctx.fillRect(b.x, b.y, b.w, b.h);
ctx.fillStyle = on ? "#1b1b1f" : "#ddd";
ctx.fillText(name, b.x + 10, b.y + b.h / 2);
});
ctx.restore();
},
});
scene.start();
return () => scene.destroy();
}scene.use(new OrbitCamera());
const sculpt = scene.use(new SculptTool({ brush: "inflate", radius: 40, symmetry: "x" }));
sculpt.brush = "crease"; // change anything at any time| Gesture | Does |
|---|---|
| Drag on a mesh | The brush |
| Ctrl + drag | The other way: in instead of out for inflate and crease, push away for pinch |
| Shift + drag | Smooth |
| Drag off every mesh | Nothing: the drag goes to the tools below, so an OrbitCamera added first still turns the view |
| Option | Default | Meaning |
|---|---|---|
brush | "inflate" | One of the brushes: "inflate", "grab", "smooth", "flatten", "pinch", "crease", "noise" |
radius | 40 | Brush radius in CSS pixels: the brush looks the same size however close the mesh is |
strength | 0.5 | 0 to 1 (more is allowed) |
falloff | "smooth" | How the brush fades to its edge (see sculptMesh) |
symmetry | none | "x" (or a list of axes): each stroke is mirrored across the mesh's own origin |
spacing | 0.15 | Distance between dabs along a stroke, in brush radii |
targets | every object | Objects that can be sculpted, or a function asked on each stroke |
filter | not sculptable: false | Which of them can be sculpted |
button | 0 | Mouse button that sculpts |
color | "#ffffff" | Color of the brush circle |
onStrokeStart(obj) | A stroke starts: save the mesh here for undo | |
onStroke(obj) | The mesh just changed | |
onStrokeEnd(obj) | The stroke ended |
How a stroke works:
- Dabs along the way. A stroke puts down a dab every
spacingradii, each along the line from the one before, socreaseandpinchmake clean grooves and ridges. A point under a stroke gets several dabs, so each one is small. - Grab works differently: the area caught at the start follows the cursor, at the depth where it was caught.
- Meshes change in place. Objects sharing a mesh change together. For undo, copy the mesh in
onStrokeStart(cloneMesh). After changing a mesh in code, callsculpt.refresh(), so the tool sees its new shape. - It needs vertices. A mesh needs plenty of them to sculpt well: build it dense, or use
remeshMesh. Objects turned or scaled, inside groups or not, are sculpted where they're drawn.
sculpt.enabled = false turns it off (no strokes, no circle) without removing it; sculpt.sculpting is the object under a stroke, or null.
All together
import {
Scene, makeShape, gridHelper, OrbitCamera, DragObject, HoverHighlight, FpsMeter,
} from "./trid/index.js";
export default function (canvas) {
const scene = new Scene(canvas, { width: 800, height: 360, camera: { fov: 0.6 }, lineWidth: 2, color: "#ffffff" });
for (let i = 0; i < 5; i++) {
scene.add({
mesh: i % 2 ? makeShape("cube", { size: 0.35, radius: 0.04, segments: 2 }) : makeShape("sphere", { r: 0.2 }),
pos: { x: (i - 2) * 0.55, y: 0.2, z: 0 },
material: { fill: `hsl(${i * 60 + 10}, 75%, 65%)`, smooth: true },
});
}
// A floor grid: helpers like it are never picked, dragged or highlighted
scene.add(gridHelper({ size: 4, divisions: 20 }));
scene.use(new OrbitCamera({ pitch: -0.35, distance: 2.6 }));
scene.use(new HoverHighlight({ exact: true })); // exact: by triangles, not bounding boxes
// Outline a shape while it's held
scene.use(new DragObject({
exact: true,
onPick: (obj) => (obj.material.wireframe = true),
onDrop: (obj) => (obj.material.wireframe = false),
}));
scene.use(new FpsMeter({ color: "#888", corner: "top-right" }));
scene.start();
return () => scene.destroy();
}