Three.js for Creators: A Beginner's Guide to 3D Web Experiences

Creating Interactive Camera Controls: Orbit, Pan, and Zoom

Section 6

Chapter 5: Interactivity: Responding to User Input

Three.js for Creators: A Beginner's Guide to 3D Web ExperiencesChapter 5: Interactivity: Responding to User Input

So far, we've been in control of our camera's perspective programmatically. But for a truly engaging 3D experience, users need to be able to explore the scene themselves! This section dives into how we can give your users intuitive camera controls like orbiting around an object, panning across the scene, and zooming in and out. Three.js provides a fantastic set of pre-built controls that make this surprisingly easy to implement.

The most common and versatile camera control in 3D applications is the OrbitControls. As the name suggests, it allows users to orbit around a target point (usually the center of your scene), pan to move the camera's position sideways or up/down, and zoom by moving the camera closer or further away from the target. Let's get started with setting this up.

First, you'll need to include the OrbitControls module. These are typically found in the examples/jsm/controls/OrbitControls.js directory of your Three.js installation or CDN. We'll import it like this:

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

Next, after you've created your scene, camera, and renderer, you'll instantiate OrbitControls, passing in your camera and renderer.domElement (which is the HTML canvas where your scene is rendered):

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

That's it for the basic setup! Now, if you run your application, you should be able to use your mouse to interact with the scene. Typically, the left mouse button allows you to orbit, the right mouse button allows you to pan, and the mouse wheel enables zooming. However, the exact behavior can be customized.

To ensure the controls update correctly on every frame, you need to call the update() method of OrbitControls within your animation loop. This is crucial for the controls to process user input and adjust the camera accordingly.

チャプターへ戻る