Skip to content

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).

js
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.

InputAction
Left dragOrbit around the target
Right drag, middle drag, or Shift + left dragPan (moves the target with the cursor)
ScrollZoom in and out
OptionDefaultMeaning
target{ x: 0, y: 0, z: 0 }Point to orbit around
distancecamera's distance to targetStarting distance
yaw, pitchcamera's yaw / pitchStarting angles
rotateSpeed0.005Radians per dragged pixel
zoomSpeed0.001Zoom amount per scroll unit
minDistance0.1Closest zoom
maxDistance100Farthest zoom
rotate, pan, zoomtrueTurn each control off with false
autoRotatefalseTurn around the target on its own (paused while dragging)
autoRotateSpeed0.5Radians per second; negative turns the other way
autoRotateDelay0Seconds 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.

Drag to orbit · right drag to pan · scroll to zoom · it auto-rotates
js
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.

InputAction
W / SForward / back
A / DLeft / right
E / QUp / down
Arrow keysTurn
Left dragLook around
Hold ShiftMove 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.

OptionDefaultMeaning
speed1Units per second
fastMultiplier3Speed multiplier while Shift is held
turnSpeed1.5Radians per second with the arrow keys
lookSpeed0.005Radians 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.

Click the canvas, then W A S D / Q E / arrows · click outside to release
js
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).

OptionDefaultMeaning
button0Mouse button that drags (0 left, 1 middle, 2 right)
filterobjects without draggable: false(obj) => boolean: which objects can be dragged
exactfalsePick by triangles instead of bounding boxes (see pickHit)
rootfalseDrag 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.

OptionDefaultMeaning
color"#ffffff"Highlight color
filterobjects without hoverable: false(obj) => boolean: which objects can be highlighted
exactfalsePick 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.

OptionDefaultMeaning
color"#ffffff"Text color
font"14px monospace"CSS font
corner"top-left""top-left", "top-right", "bottom-left" or "bottom-right"
interval0.5Seconds 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.

js
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
OptionDefaultMeaning
orbitthe scene's first OrbitCameraCamera controls to turn. Without one, the gizmo only shows the axes
corner"top-right""top-right", "top-left", "bottom-right" or "bottom-left"
size42Radius in CSS pixels
margin14Distance from the corner in CSS pixels: a number, or { x, y }
duration0.35Seconds 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).

Click a shape to select it · drag a handle · 1 move, 2 rotate, 3 scale · click the corner axes to turn the view
js
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();
  };
}
ModeHandlesDrag
"move"X, Y, Z arrowsMoves along that world axis
"rotate"X, Y, Z ringsTurns 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 squareStretches along that axis; the center square scales evenly (×2 per 100 px dragged right, smaller to the left)
OptionDefaultMeaning
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
size70Handle length in CSS pixels (the same on screen at any distance)
applytrueChange 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
outlinefalseOutline 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.

pivotWhere
"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) => pointAsked every frame: for a pivot your app keeps in its own data (return null for no handles)
js
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 data

gizmo.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:

js
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:

js
{ 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: uniform

SelectionOutline ​

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.

js
const selection = scene.use(new SelectionOutline());
selection.targets = [chair]; // change at any time; [] outlines nothing

The 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.

OptionDefaultMeaning
targets[]Objects to outline, or a function asked every frame, like () => gizmo.targets
color"#ffa64d"Line color
width2Line width in CSS pixels
hidden0.35Opacity 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.

drag on the ball to sculpt · Ctrl + drag: the other way · Shift + drag: smooth · click a brush above · drag off the ball to orbit
js
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();
}
js
scene.use(new OrbitCamera());
const sculpt = scene.use(new SculptTool({ brush: "inflate", radius: 40, symmetry: "x" }));
sculpt.brush = "crease"; // change anything at any time
GestureDoes
Drag on a meshThe brush
Ctrl + dragThe other way: in instead of out for inflate and crease, push away for pinch
Shift + dragSmooth
Drag off every meshNothing: the drag goes to the tools below, so an OrbitCamera added first still turns the view
OptionDefaultMeaning
brush"inflate"One of the brushes: "inflate", "grab", "smooth", "flatten", "pinch", "crease", "noise"
radius40Brush radius in CSS pixels: the brush looks the same size however close the mesh is
strength0.50 to 1 (more is allowed)
falloff"smooth"How the brush fades to its edge (see sculptMesh)
symmetrynone"x" (or a list of axes): each stroke is mirrored across the mesh's own origin
spacing0.15Distance between dabs along a stroke, in brush radii
targetsevery objectObjects that can be sculpted, or a function asked on each stroke
filternot sculptable: falseWhich of them can be sculpted
button0Mouse 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 spacing radii, each along the line from the one before, so crease and pinch make 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, call sculpt.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 ​

Hover a shape · drag it · Shift + drag to push / pull · drag empty space to orbit
js
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();
}