Raycaster and Object Interaction

Convert pointer coordinates to NDC and use Raycaster for clicking, hovering, highlighting, and model property panels.

🎯 Introduction

By the end of this article, you will be able to identify the 3D object a user clicks, handle hover highlights and selection, and display information about the hit object in a Vue panel.

🧱 From screen coordinates to NDC

Pointer events provide page pixel coordinates, while Raycaster needs normalized device coordinates (NDC). Both x and y range from -1 to 1, with the origin at the canvas center.

const pointer = new THREE.Vector2();

const updatePointer = (event) => {
    const rect = renderer.domElement.getBoundingClientRect();
    pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
    pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
};

Do not calculate this directly with window.innerWidth: the canvas may occupy only part of the page or sit inside a scrolling container.

🎯 Finding hits with Raycaster

setFromCamera casts a ray using the camera and NDC. intersectObjects returns intersections sorted by distance:

const raycaster = new THREE.Raycaster();
const selectable = [cube, sphere];

const pick = (event) => {
    updatePointer(event);
    raycaster.setFromCamera(pointer, camera);

    const hits = raycaster.intersectObjects(selectable, true);
    const selected = hits[0]?.object || null;
    if (selected) {
        console.log(selected.name, selected.userData);
    }
};

renderer.domElement.addEventListener('click', pick);

Passing true as the second argument checks children recursively, which is useful for picking glTF models. The hit may be an internal mesh, so you often need to follow parent upward to the root carrying application userData.

✨ Highlighting and property panels

Save the original material state when highlighting a selection so repeated clicks do not prevent restoration:

let selected = null;
let oldColor = null;

const selectObject = (object) => {
    if (selected?.material?.color && oldColor) {
        selected.material.color.copy(oldColor);
    }

    selected = object;
    if (!selected?.material?.color) return;

    oldColor = selected.material.color.clone();
    selected.material.color.set(0xffaa33);
};

In Vue, copy selected.userData into reactive state and use a regular template to display its name, type, and application ID. Three.js manages canvas objects, while Vue manages the surrounding information panel, keeping responsibilities clear.

This demo contains two cubes with name and userData.id properties. Clicking a cube uses Raycaster to find the intersected mesh, saves its original color, and displays its name and application ID:

Click the blue or orange cube

Hover interactions repeat picking on pointermove and must handle the pointer leaving an object. To avoid unnecessary material changes, update the highlight only when the hit object changes.

🧰 Tools for dragging objects

To let users directly move, rotate, or scale the selected object, use the TransformControls add-on:

import { TransformControls } from 'three/addons/controls/TransformControls.js';

const transformControls = new TransformControls(camera, renderer.domElement);
transformControls.attach(selected);
scene.add(transformControls.getHelper());

When using it with OrbitControls, temporarily disable OrbitControls rotation during dragging so both controls do not respond to the same pointer events.

Raycaster casts a test ray from the camera into the scene; it does not find objects through DOM elements. Hits depend on the camera, canvas coordinates, object visibility, and geometry bounds.

🧾 Summary

  • Convert pointer positions to NDC using the canvas rectangle.
  • setFromCamera creates the ray; intersectObjects returns hit objects.
  • Use the recursive argument true to check glTF children.
  • Save and restore the original material state for selection highlights.
  • Vue suits selected-object property panels, while Three.js handles the 3D canvas.
  • TransformControls edits object position, rotation, and scale.

❓ Questions and answers

Q1: Why is the click position offset?

You may be using window dimensions instead of canvas dimensions, or forgetting to subtract the canvas's top-left position from getBoundingClientRect().

Q2: Why does picking return an internal model part?

Raycaster returns the mesh that actually intersects the ray. Follow its parents to the application root carrying userData.modelId.

Q3: Why can I not restore the material color after clicking?

Without saving the original color, you can only guess it later. Save it with color.clone() before selection and copy it back on deselection.

🧪 Exercise

Create three named shapes. On click, log the hit object's name and userData.id, and restore the previously selected object's original color.

// Write your code here

🎉 Users can now click 3D objects. Next, you will cover renderer configuration, responsive sizing, and performance constraints.