How to Use OrbitControls in Three.js

Integrating interactive camera controls is essential for exploring 3D scenes. This guide provides a straightforward, step-by-step approach to implementing OrbitControls in Three.js, allowing users to effortlessly rotate, zoom, and pan the camera around a target object using mouse or touch inputs.

Step 1: Import OrbitControls

To use OrbitControls, you must import it alongside the core Three.js library. If you are using ES modules (via npm or a CDN like unpkg), import it as follows:

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

Step 2: Initialize the Controls

Once your scene, camera, and renderer are established, instantiate OrbitControls. You must pass the camera and the renderer’s DOM element as arguments so the controls know which camera to manipulate and which element to listen to for mouse events.

const controls = new OrbitControls(camera, renderer.domElement);

Step 3: Update the Controls in the Animation Loop

For the controls to respond to user input and animate smoothly, you must update them inside your render loop.

function animate() {
    requestAnimationFrame(animate);

    // Required if controls.enableDamping or controls.autoRotate are set to true
    controls.update();

    renderer.render(scene, camera);
}
animate();

Step 4: Customize Control Behavior (Optional)

You can easily adjust the behavior of the rotation, zoom, and panning. Here are some of the most common configuration properties:

Complete Code Example

Below is a complete, minimal implementation showing how OrbitControls integrates into a basic Three.js application.

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

// 1. Scene setup
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 2, 5);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// 2. Add a simple 3D object
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// 3. Initialize OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; 
controls.dampingFactor = 0.05;

// 4. Animation loop
function animate() {
    requestAnimationFrame(animate);
    
    // Update controls for damping effect
    controls.update(); 
    
    renderer.render(scene, camera);
}
animate();