As creators, we want our 3D experiences to feel alive and responsive. A crucial part of this is allowing users to interact with our creations. This means understanding how to detect and react to user input, such as mouse clicks, movements, or keyboard presses. In Three.js, we tap into the browser's built-in event system to achieve this.
The browser is constantly listening for user actions. When an action occurs, it generates an 'event'. These events can be about a multitude of things, but for our 3D world, we're primarily interested in events related to the HTML element that contains our Three.js canvas. Common events include: click, mousemove, mousedown, mouseup, keydown, and keyup.
To listen for these events, we use the addEventListener method on our HTML element. This method takes two main arguments: the type of event we want to listen for (e.g., 'click') and a callback function that will be executed whenever that event occurs.
const canvas = document.querySelector('canvas.webgl');
canvas.addEventListener('click', (event) => {
console.log('The canvas was clicked!');
});The callback function receives an event object as an argument. This object contains valuable information about the event that just happened. For mouse events, for example, it includes properties like clientX and clientY, which give you the coordinates of the mouse pointer relative to the viewport.
canvas.addEventListener('mousemove', (event) => {
console.log(`Mouse X: ${event.clientX}, Mouse Y: ${event.clientY}`);
});It's important to remember that these coordinates are relative to the entire browser window. When working with Three.js, we often need to translate these screen coordinates into something meaningful within our 3D scene, like the position of a raycaster or the coordinates of a clicked object. We'll explore how to do this in later sections.
graph TD
A[User Action (e.g., Click)] --> B{Browser Fires Event};
B --> C[Event Listener on Canvas];
C --> D{Callback Function Executes};
D --> E[Access Event Data (e.g., coordinates)];
E --> F[Process Data in Three.js Scene];