SELECT A 3D CUBE
THREE.JS RAYCASTER

By Shane Brumback · Updated · Free · 20 minute read

To select a 3D object in Three.js, convert the pointer position to normalized device coordinates, aim a THREE.Raycaster from the camera with setFromCamera, and call intersectObjects. The first hit is the object under the cursor, so you can recolor it, move it or open a menu.

Raycaster Object picking Click, hover and touch

Press Live Demo to click the cube yourself, then follow the steps and copy the full code.

See it live

LIVE DEMO

The spinning cube behind this page is the live demo. Press the button to go full screen, then click or tap the cube to select it. It turns green and glides toward the camera, and a second click sends it back. With a mouse it lights up when you hover, and you can drag to orbit without selecting it.

Press Esc or the X to exit.

Introduction

New to Three.js? Start with Your First Three.js Scene, then come back here.

Clicking things is how players interact with a 3D world: picking a unit, opening a door, choosing a menu item or grabbing an item off the ground. In Three.js you do that with a raycaster. In this tutorial you build one small scene, a glowing blue cube on a grid, and make it react to the mouse and to touch. Hover and it lights up, click or tap and it turns green and glides toward the camera, click again and it goes home.

The code is current for Three.js r160. It uses pointer events, so one set of listeners covers mouse, touch and pen. It also tells a real click apart from an OrbitControls drag, which is the bug most raycasting examples leave in. Everything loads from a CDN, so you need no install or build tools.

How Raycasting Works

A screen is flat, but your scene is 3D, so a click alone does not tell you what you clicked. A raycaster solves that by shooting a straight line from the camera, through the spot you clicked on the screen, out into the scene. Every mesh that line passes through is a hit. Three.js gives you the hits sorted from nearest to farthest, and each one includes the object, the distance, the exact point in world space and the face that was hit.

  1. Read the pointer position from the event.
  2. Convert it to normalized device coordinates, from -1 to +1.
  3. Aim the ray with raycaster.setFromCamera(pointer, camera).
  4. Test only the objects you care about with raycaster.intersectObjects(list).
  5. Use hits[0], the closest one, to change your scene.

Frequently Asked Questions

What is a raycaster in Three.js?

THREE.Raycaster casts an invisible ray from a point in a direction and reports every object the ray passes through, sorted nearest first. For mouse picking you aim it from the camera through the pointer position with raycaster.setFromCamera(pointer, camera), then call intersectObjects to see what is under the cursor.

How do I select a 3D object with a mouse click in Three.js?

Listen for a pointer event on renderer.domElement, convert the pointer position to normalized device coordinates (-1 to +1 on both axes), call raycaster.setFromCamera(pointer, camera), and call raycaster.intersectObjects(objects). If the result is not empty, hits[0].object is the object you clicked, so change its material color or move it.

Why do I need normalized device coordinates for raycasting?

setFromCamera expects the screen position as normalized device coordinates, where the center of the canvas is (0, 0), the left edge is x = -1, the right edge is x = +1, the top is y = +1 and the bottom is y = -1. Compute them from clientX and clientY using the canvas getBoundingClientRect so picking stays accurate when the canvas is not full screen.

How do I stop OrbitControls drags from selecting the object?

Save the pointer position on pointerdown and compare it on pointerup. If the pointer moved more than a few pixels (6 in this tutorial), treat it as a camera drag and skip the raycast. Only a short press and release with almost no movement counts as a click.

Does Three.js raycasting work on phones and touch screens?

Yes. Pointer events fire for touch, mouse and pen, so the same pointerdown and pointerup code selects the cube with a tap. Set touch-action: none on the canvas so the browser does not scroll the page while you drag, and skip hover effects for touch because phones have no hover.

How do I select one object out of many in Three.js?

Put every clickable mesh in an array and pass it to raycaster.intersectObjects(array). The first hit is the closest object to the camera. If your objects are Groups or loaded GLB models, pass true as the second argument so their child meshes are tested, then walk up from hits[0].object to the parent you care about.

Is this Three.js raycaster tutorial free?

Yes. Reading the tutorial and copying the full code are free. The full-screen Live Demo needs a free Google sign-in.

How to Build It, Step by Step

Each step adds one idea. The snippets go inside one <script type="module">, in order, after these two imports:

import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

Step 1: Set up the scene, camera, renderer and orbit controls

Every Three.js project starts with a scene to hold objects, a PerspectiveCamera to look at them and a WebGLRenderer that draws to a canvas. A dark background with matching Fog makes the grid fade out instead of ending at a hard edge. OrbitControls let you drag to look around the cube; panning is off and maxPolarAngle stops the camera from going under the grid.

// STEP 1: Scene, camera, renderer and orbit controls
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b16);
scene.fog = new THREE.Fog(0x070b16, 16, 42);    // the grid fades into the dark
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(4.5, 3.2, 7);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.8, 0);
controls.enableDamping = true;
controls.enablePan = false;
controls.minDistance = 4;
controls.maxDistance = 14;
controls.maxPolarAngle = Math.PI * 0.48;        // never look up from under the grid

Step 2: Add the cube, a grid and lights

The cube is a Mesh: a BoxGeometry plus a MeshStandardMaterial that reacts to light. A HemisphereLight fills the shadows and a DirectionalLight gives the cube bright and dark sides so you can see it turn. The emissive color makes the cube glow, and we change it later to show hover and selection. The selectable array lists the only objects the raycaster is allowed to pick, which keeps it fast and stops the grid from being picked.

// STEP 2: Add the cube, a grid and lights
scene.add(new THREE.HemisphereLight(0x9fc4ff, 0x0b1020, 1.2));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.2);
keyLight.position.set(5, 8, 4);
scene.add(keyLight);
scene.add(new THREE.GridHelper(40, 40, 0x2ad1d6, 0x1b3a4a));

const BLUE = 0x2a6bff, GREEN = 0x00ff6a;
const GLOW = { idle: new THREE.Color(0x0a1e5a), hover: new THREE.Color(0x2350d8), selected: new THREE.Color(0x0a5a2e) };
const material = new THREE.MeshStandardMaterial({ color: BLUE, emissive: GLOW.idle.clone(), roughness: 0.35, metalness: 0.1 });
const cube = new THREE.Mesh(new THREE.BoxGeometry(1.6, 1.6, 1.6), material);
const home = new THREE.Vector3(0, 0.8, 0);
cube.position.copy(home);
scene.add(cube);
const selectable = [cube];                      // only these objects can be picked

Step 3: Turn the pointer into a ray and find what it hits

A Raycaster shoots an invisible line from the camera through the point you clicked. It needs the pointer in normalized device coordinates, where x runs from -1 on the left to +1 on the right and y from +1 at the top to -1 at the bottom. We measure against the canvas with getBoundingClientRect, so it still works when the canvas is not full screen. raycaster.setFromCamera(pointer, camera) aims the ray, and intersectObjects returns every hit sorted nearest first, so hits[0].object is the thing you clicked.

// STEP 3: Turn the pointer into a ray and find what it hits
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pick(event) {
    const rect = renderer.domElement.getBoundingClientRect();
    pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;   // -1 (left) to +1 (right)
    pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;  // +1 (top) to -1 (bottom)
    raycaster.setFromCamera(pointer, camera);
    const hits = raycaster.intersectObjects(selectable, false);      // sorted nearest first
    return hits.length > 0 ? hits[0].object : null;
}

Step 4: Hover with the mouse, and tell a click from a drag

Pointer events work for mouse, touch and pen with one set of listeners. On pointermove we pick under the mouse and switch the cursor to a pointer hand, so the cube visibly lights up when you can click it. Phones have no hover, so that part only runs for a mouse. Because dragging also orbits the camera, we remember where the pointer went down and only count it as a click if it moved less than 6 pixels before pointerup.

// STEP 4: Hover with the mouse, and tell a click from a drag
let hovered = null;
renderer.domElement.addEventListener('pointermove', (event) => {
    if (event.pointerType !== 'mouse') return;  // phones have no hover
    hovered = pick(event);
    renderer.domElement.style.cursor = hovered ? 'pointer' : 'grab';
});
const downAt = new THREE.Vector2();
renderer.domElement.addEventListener('pointerdown', (event) => downAt.set(event.clientX, event.clientY));
renderer.domElement.addEventListener('pointerup', (event) => {
    const moved = downAt.distanceTo(new THREE.Vector2(event.clientX, event.clientY));
    if (moved > 6) return;                      // more than 6px means you were orbiting
    if (pick(event)) toggleSelect();
});

Step 5: React to the selection

toggleSelect flips a selected flag, turns the cube green and sets a goal position part of the way toward the camera, wherever you have orbited to. Clicking again turns it blue and sends it home. The click only changes state; the animation loop does the moving, so the motion stays smooth.

// STEP 5: React to the selection
let selected = false;
const goal = home.clone();
function toggleSelect() {
    selected = !selected;
    material.color.set(selected ? GREEN : BLUE);
    if (selected) {
        // glide part of the way toward wherever the camera is now
        goal.copy(camera.position).sub(controls.target).multiplyScalar(0.45).add(home);
    } else {
        goal.copy(home);
    }
}

Step 6: Animate with smooth, frame-rate independent motion

The loop turns the cube a little each frame and eases its position toward the goal with lerp. Using 1 - Math.exp(-6 * dt) as the blend amount, with dt from THREE.Clock, gives the same smooth glide at 30, 60 or 144 frames per second. The emissive glow eases the same way between the idle, hover and selected colors, and the resize listener keeps the picture sharp when the window changes size.

// STEP 6: Animate with smooth, frame-rate independent motion
const clock = new THREE.Clock();
function animate() {
    requestAnimationFrame(animate);
    const dt = Math.min(clock.getDelta(), 0.05);
    cube.rotation.x += 0.35 * dt;
    cube.rotation.y += 0.5 * dt;
    cube.position.lerp(goal, 1 - Math.exp(-6 * dt));                 // ease toward the goal
    const glow = selected ? GLOW.selected : (hovered ? GLOW.hover : GLOW.idle);
    material.emissive.lerp(glow, 1 - Math.exp(-10 * dt));
    controls.update();
    renderer.render(scene, camera);
}
animate();

window.addEventListener('resize', () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
});

The Full Code

Copy this into a file named index.html and open it in any modern browser, or press Launch to run it in a new tab right now. It is the same scene that is running behind this page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Three.js Raycaster: Select a 3D Cube</title>
    <style> body { margin: 0; overflow: hidden; background: #070b16; } canvas { display: block; touch-action: none; } </style>
    <script type="importmap">
    {
        "imports": {
            "three": "https://unpkg.com/three@0.160.0/build/three.module.js",
            "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
        }
    }
    </script>
</head>
<body>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

// STEP 1: Scene, camera, renderer and orbit controls
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b16);
scene.fog = new THREE.Fog(0x070b16, 16, 42);    // the grid fades into the dark
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(4.5, 3.2, 7);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.8, 0);
controls.enableDamping = true;
controls.enablePan = false;
controls.minDistance = 4;
controls.maxDistance = 14;
controls.maxPolarAngle = Math.PI * 0.48;        // never look up from under the grid

// STEP 2: Add the cube, a grid and lights
scene.add(new THREE.HemisphereLight(0x9fc4ff, 0x0b1020, 1.2));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.2);
keyLight.position.set(5, 8, 4);
scene.add(keyLight);
scene.add(new THREE.GridHelper(40, 40, 0x2ad1d6, 0x1b3a4a));

const BLUE = 0x2a6bff, GREEN = 0x00ff6a;
const GLOW = { idle: new THREE.Color(0x0a1e5a), hover: new THREE.Color(0x2350d8), selected: new THREE.Color(0x0a5a2e) };
const material = new THREE.MeshStandardMaterial({ color: BLUE, emissive: GLOW.idle.clone(), roughness: 0.35, metalness: 0.1 });
const cube = new THREE.Mesh(new THREE.BoxGeometry(1.6, 1.6, 1.6), material);
const home = new THREE.Vector3(0, 0.8, 0);
cube.position.copy(home);
scene.add(cube);
const selectable = [cube];                      // only these objects can be picked

// STEP 3: Turn the pointer into a ray and find what it hits
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pick(event) {
    const rect = renderer.domElement.getBoundingClientRect();
    pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;   // -1 (left) to +1 (right)
    pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;  // +1 (top) to -1 (bottom)
    raycaster.setFromCamera(pointer, camera);
    const hits = raycaster.intersectObjects(selectable, false);      // sorted nearest first
    return hits.length > 0 ? hits[0].object : null;
}

// STEP 4: Hover with the mouse, and tell a click from a drag
let hovered = null;
renderer.domElement.addEventListener('pointermove', (event) => {
    if (event.pointerType !== 'mouse') return;  // phones have no hover
    hovered = pick(event);
    renderer.domElement.style.cursor = hovered ? 'pointer' : 'grab';
});
const downAt = new THREE.Vector2();
renderer.domElement.addEventListener('pointerdown', (event) => downAt.set(event.clientX, event.clientY));
renderer.domElement.addEventListener('pointerup', (event) => {
    const moved = downAt.distanceTo(new THREE.Vector2(event.clientX, event.clientY));
    if (moved > 6) return;                      // more than 6px means you were orbiting
    if (pick(event)) toggleSelect();
});

// STEP 5: React to the selection
let selected = false;
const goal = home.clone();
function toggleSelect() {
    selected = !selected;
    material.color.set(selected ? GREEN : BLUE);
    if (selected) {
        // glide part of the way toward wherever the camera is now
        goal.copy(camera.position).sub(controls.target).multiplyScalar(0.45).add(home);
    } else {
        goal.copy(home);
    }
}

// STEP 6: Animate with smooth, frame-rate independent motion
const clock = new THREE.Clock();
function animate() {
    requestAnimationFrame(animate);
    const dt = Math.min(clock.getDelta(), 0.05);
    cube.rotation.x += 0.35 * dt;
    cube.rotation.y += 0.5 * dt;
    cube.position.lerp(goal, 1 - Math.exp(-6 * dt));                 // ease toward the goal
    const glow = selected ? GLOW.selected : (hovered ? GLOW.hover : GLOW.idle);
    material.emissive.lerp(glow, 1 - Math.exp(-10 * dt));
    controls.update();
    renderer.render(scene, camera);
}
animate();

window.addEventListener('resize', () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>

Common Raycasting Mistakes

  • Using window size when the canvas is smaller. If the canvas is not full screen, divide by the canvas getBoundingClientRect(), not window.innerWidth, or clicks land in the wrong place.
  • Forgetting to flip y. Screen y grows downward, but normalized y is +1 at the top, so the formula needs the minus sign.
  • Selecting on every drag. With OrbitControls, a drag ends in a pointerup too. Check how far the pointer moved first.
  • Missing child meshes. Groups and loaded GLB models keep their meshes as children, so pass true to intersectObjects to test them.
  • Raycasting against everything. Testing the whole scene each mouse move is slow on big levels. Keep a short list of selectable objects.

What To Try Next

  • Add three more cubes to selectable and let only one be selected at a time.
  • Use hits[0].point to drop a small marker exactly where you clicked.
  • Color just the clicked face using hits[0].face and a material array.
  • Turn the cube into a button for a 3D menu, as in How to Program a 3D Menu.
  • See raycasts used for gameplay in spreading pickups on terrain.