ThreeJS — Adding the Orbit Controls
In the previous article, I showed you the minimum code to run a ThreeJS scene in the browser. You should have a main.js file like the following:
However, it needs the most vital part: interactivity.
The scene was a static render without any user interaction. In this article, we will add the Orbit Controls, allowing us to rotate the scene around its center.
In the main.js files, just behind the line where importing the ThreeJS library, we need to import the OrbitControls module:
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
At the end of the main.js file, we can now create a new OrbitControls instance, referencing the same camera and canvas we are using to render the ThreeJS scene. We can also enable the autoRotate…
// Add OrbitControls
const controls = new OrbitControls(camera, canvas)
controls.autoRotate = true
No error so far in the browser's Console, but the OrbitControls are not working. Nothing happens if we click 'n drag inside the browser window, nor is the autorotate working. Why?
Because the scene is missing an essential feature: the Animation Loop
Right now, we're rendering the scene only once when we call renderer.render(scene, camera)
, but we need to do the render a lot of times per second to give the illusion of movement. To do this, we need to use an Animation Loop.
In the main.js file, add the following block of code in which we create the animate function that will call itself using the requestAnimationFrame method:
// Animate Loop
function animate() {
// Render the Scene
renderer.render(scene, camera)
// Update the controls
controls.update()
// Call the animate function again on the next frame
requestAnimationFrame(animate)
}
animate()
As you run npm run dev
command and visit http://localhost:3000/.
You should see a green rotating cube. Now, If you click ‘n drag in the <canvas>, you can orbit around the cube and override the autorotate.
To finalize this tutorial, I would like to add the last feature: the ability to resize the window browser and update the ThreeJS scene accordingly.
If you try to resize the browser's window, you should notice that the <canvas>
element is not updating its size:
To update the <canvas>
, we need to:
- Update the render size
- Update the camera aspect ratio and projection matrix
We can do this by adding an event listener to the resize event. Add this block to the end of the main.js file, and you should see the <canvas>
updating now.
// Add an event listener to the window resize
window.addEventListener(‘resize’, function() {
renderer.setSize(window.innerWidth, window.innerHeight)
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
})
Stay tuned for the next article, in which we will replace the cube with more exciting stuff.