What are OrbitControls in three.js?

The three.js library in JavaScript uses WebGL to render animations on the web. We use OrbitControls to make the camera orbit a target.

In this Answer, we see how these controls help a user interact with the targets.

Note: To learn more about three.js, please click here.

Syntax

The syntax for the initialization of OrbitControls is as follows:

const controls = new OrbitControls(camera, canvas);

Parameters

The initialization of the controls takes in two parameters:

  • camera: This is the THREE.Camera and is already a part of the scene.
  • canvas: This is the HTML canvas element in which we render our scene.

Updating the controls

After we initialize the controls, we call the update method on the controls object to update them in every frame.

We do this by calling the update method inside the function that renders the animations.

const animate = () => {
// Update the orbital controls
controls.update()
// Render
renderer.render(scene, camera)
// Call and animate again on the next frame
window.requestAnimationFrame(animate();
}
animate();

Example

The following is an example of a normal three.js application we add OrbitControls to it. The user can grab hold of the object and move it around as they please.

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Copyright ©2024 Educative, Inc. All rights reserved