In HTML, every button has its own events. 3D isn't like that: the canvas is one big picture, and the browser only knows "there was a click at point (x, y) of the canvas". Which product is at that point is yours to find out. Picture a buyer pointing at the glass of Raka's shop display: draw a straight line from the buyer's eye through their fingertip on the glass, and the first product that line passes through is the one they mean. That line is called a ray, and the three.js tool that casts it is the Raycaster.
In this lesson Raka's 3D display holds the Coffee Print Mug and the Coffee Print Tee box: the camera can be turned, products light up when pointed at, and a click changes their print colour.
OrbitControls: turning the camera
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; // r186
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // glides smoothly after release
controls.enableZoom = false; // the mouse wheel still scrolls the page
renderer.setAnimationLoop(() => {
controls.update(); // required when enableDamping = true
renderer.render(scene, camera);
});
- Drag with the left button: the camera circles
controls.target((0, 0, 0) by default). Right button or Ctrl/Shift + drag: pans. Mouse wheel: in and out (zoom). - The turn is 2π × the drag distance / the canvas height: on a 240 px tall canvas, a 240 px drag = one full turn.
- With
enableDamping, eachupdate()applies only 5% (dampingFactor0.05) of the rest of the turn, the rest following in later frames. Withoutcontrols.update()in the loop, that rest is left hanging: the camera lags behind the finger and stops dead. enableZoom = falsefor a product embedded in an article: OrbitControls catches the mouse wheel, so a reader who wants to scroll zooms instead.- OrbitControls sets
touch-action: noneon the canvas. On a phone, a swipe that starts on the canvas never scrolls the page. A screen-tall canvas can trap the thumb: make it shorter, or usetouch-action: pan-yso an up-down swipe still scrolls (a left-right drag still turns).
The pointer becomes NDC
The Raycaster needs the pointer's position in NDC (Normalized Device Coordinates): -1 at the left to 1 at the right, -1 at the bottom to 1 at the top, (0, 0) in the middle of the canvas, whatever its size.
const pointer = new THREE.Vector2();
const r = renderer.domElement.getBoundingClientRect(); // the canvas's position and size on the page
pointer.x = ((e.clientX - r.left) / r.width) * 2 - 1;
pointer.y = -((e.clientY - r.top) / r.height) * 2 + 1;
Example: a canvas at left 40, top 100, 320 × 240 in size; the pointer at (120, 160). x: (120 - 40) / 320 = 0.25, times 2 minus 1 = -0.5. y: (160 - 100) / 240 = 0.25, times 2 = 0.5, flipped then plus 1 = 0.5. Y flips because on a page y grows downwards, in NDC upwards.
The formula that uses window.innerWidth, pointer.x = (e.clientX / window.innerWidth) * 2 - 1, is only right for a canvas as wide as the window. Raka's window is 1280 × 800, his canvas at left 480, top 280. The pointer in the middle of the mug (clientX 592, clientY 400): the right formula gives x = -0.3 (the mug), the window formula gives x = 592 / 1280 × 2 - 1 = -0.075, the empty gap between the mug and the shirt box. Nothing lights up.
Raycaster: a ray from the camera
const raycaster = new THREE.Raycaster();
const products = [mug, shirt];
function productAt(e) {
// ...pointer.x and pointer.y as above
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(products)[0]; // the nearest
let thing = hit ? hit.object : null;
while (thing && !products.includes(thing)) thing = thing.parent; // handle climbs to mug
return thing;
}
setFromCameramakes a ray from the camera's position through the pointer.intersectObjectstests it against every triangle and returns an array, nearest first:distance,point(the 3D point hit),object,uv(the spot on the texture),faceIndex. Empty[]when nothing is hit.- It is recursive by default, so children like the handle are checked too, and
objectis the mesh actually hit. Over the handle,intersects[0].objectishandle, notmug: climb throughparent.
Results from the display (camera at (0, 1.2, 5.2)):
| NDC | object | distance | uv |
|---|---|---|---|
| (-0.30, 0.00) | mug body | 4.64 | (0.62, 0.60) |
| (0.50, 0.00) | shirt | 5.25 | (0.57, 0.55) |
| (0.00, -0.25) | handle | 5.05 | (0.20, 0.17) |
| (-0.05, 0.05) | [] |
Hover and click
let highlighted = null;
function highlight(thing) {
if (thing === highlighted) return;
if (highlighted) for (const m of highlighted.userData.materials) m.emissive.set('#000000');
if (thing) for (const m of thing.userData.materials) m.emissive.set('#333333');
renderer.domElement.style.cursor = thing ? 'pointer' : 'grab';
highlighted = thing;
}
renderer.domElement.addEventListener('pointermove', (e) => highlight(productAt(e)));
let press = null;
renderer.domElement.addEventListener('pointerdown', (e) => { press = [e.clientX, e.clientY]; });
renderer.domElement.addEventListener('click', (e) => {
if (!press || Math.hypot(e.clientX - press[0], e.clientY - press[1]) > 4) return; // that was a drag
const thing = productAt(e);
if (thing) changeColor(thing);
});
function changeColor(thing) {
const s = thing.userData.print; // { canvas, texture, index }
s.index = (s.index + 1) % COLORS.length; // brown #c47a3d, green #7fb069
drawPrint(s.canvas, COLORS[s.index]);
s.texture.needsUpdate = true; // send the canvas to the GPU again
}
emissiveis light the material gives off itself;#333333makes it a little brighter.userData.materialsholds that product's own materials only: a material shared by two products would light up on both.clickstill fires after someone turns the camera, so check the distance frompointerdown: more than 4 px means a drag.- The print is redrawn on its canvas, then
needsUpdate = true. Without it the GPU keeps the old picture.
A keyboard alternative
Everything the pointer can do must be doable from the keyboard. controls.listenToKeyEvents(window) only gives the arrows for panning, and Shift + arrow turns 2π / 240 ≈ 1.5° per press: too little. That angle is multiplied by controls.keyRotateSpeed (default 1), so controls.keyRotateSpeed = 10 turns 15° per press, but users still have to know the Shift + arrow combination. Clearer: plain buttons (reachable with Tab and Enter by themselves).
const AXIS_Y = new THREE.Vector3(0, 1, 0);
function turnCamera(angle) {
camera.position.sub(controls.target).applyAxisAngle(AXIS_Y, angle).add(controls.target);
controls.update();
}
leftButton.addEventListener('click', () => turnCamera(-Math.PI / 12)); // 15°
mugColorButton.addEventListener('click', () => changeColor(mug));
In React Three Fiber (the next lesson), you just write <mesh onClick={...} onPointerOver={...}>: R3F runs the raycasting for you, with the same Raycaster underneath.
⚠️ Five complaints a 3D display often gets
- NDC from
window.innerWidthfor a small canvas: hover and click miss. UsegetBoundingClientRect(). hit.object === mug: the handle (a child) never matches. Climb throughparent.enableDampingwithoutcontrols.update()in the loop: the camera lags and stops dead.- A click after turning the camera: the colour changes too. Tell clicks from drags.
- Forgetting
texture.needsUpdate = true: the canvas has changed, the mug keeps the old colour.
TL;DR: The canvas doesn't know what was clicked; the Raycaster finds it. Turn the pointer into NDC relative to the canvas (getBoundingClientRect, y flipped), raycaster.setFromCamera(pointer, camera), then intersectObjects(products): an array, nearest first (object, distance, point, uv), children included, climb through parent. Hover: emissive + the cursor; click (not drag): redraw the print, then needsUpdate. OrbitControls from 'three/addons/controls/OrbitControls.js': damping needs controls.update() every frame, enableZoom = false in an article, and it sets touch-action: none. Give every pointer action a keyboard button. In R3F, onClick and onPointerOver go right on the <mesh>.
⚡ The pointer becomes NDC
Write:
const r = renderer.domElement.getBoundingClientRect();
pointer.x = ((e.clientX - r.left) / r.width) * 2 - 1;
pointer.y = -((e.clientY - r.top) / r.height) * 2 + 1;
Meaning: NDC runs from -1 to 1 inside the canvas, (0, 0) in its middle, and y points up. Work it out from the canvas's corner and size, not from window.innerWidth, unless the canvas is as wide as the window.
⚡ A ray from the camera
Write:
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(products)[0];
Guess first: the pointer is over the mug's handle. Is hit.object the mug?
No, it's handle, the mug's child. Climb through parent until you reach the product.
Meaning: The canvas only knows there was a click at point (x, y). The Raycaster casts a ray from the camera through the pointer and returns what it hits, nearest first. That's how you find which product was pointed at or clicked.
⚡ Click or drag?
Meaning: click still fires after someone turns the camera. Keep the pointerdown position, and if the distance is more than 4 px, it was a drag. After redrawing the print on its canvas, set needsUpdate = true.