Skip to Content

Trackball Controls in three.js

|Three.js|0 Comments

This tutorial explains how to rotate the camera with the mouse in three.js. This can be accomplished using the built-in TrackballControls.js. Test it out on the below. Rotating the object around by holding down the left mouse button and dragging. Zoom with the middle and pan from side to side with the right mouse button. Download the source code for this tutorial.

This example rotates the camera around the object in all directions, to take a look at a different kind of mouse tracking technique where the mouse rotates the scene on a view plane please see Rotating View with the Mouse in Three.js or the Smooth Camera Rotation example.

If you’ve downloaded the example files from the three.js website, you can find TrackballControls.js in: examples>js>controls.

Include the file

Start by including?TrackballControls.js in your html file:

<script src="js/controls/OnepixMouseTracking.js"></script>


Set Up the Camera

Set up your camera in the usual way.? You may have to tweak this according to the size of your model. In this example, the camera is moved 3 units closer to the object.

camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 10000 );
camera.position.z = 5;


Add the Camera Controls

Make a new instance of THREE.TrackballControls which will automatically bind the mousedown button controls to the camera rotation, pan and zoom.

cameraControls = new THREE.TrackballControls(camera, renderer.domElement);, 0, 0);

make sure cameraControls is defined at the top of your document

var cameraControls


Update the Camera Controls

You should have a function called “update” or “animate”. This will be the function that is called repeatedly to perform task like animation or what we’re doing.? The only thing we’re concerned about here is the cameraControls.update function. Simply call it and add the delta (difference in time between one update call and another).

function animate() {

var delta = clock.getDelta();
renderer.render(scene, camera);


if you’re wondering where the clock variable is from, you can call it at the top of your file like this which is a timer built into three.js.

var clock = new THREE.Clock();


That’s it! If all went well you should be able to rotate the object around by holding down the left mouse button and dragging. Zoom with the middle mouse button and pan with the right mouse button.

Related Posts

Share This

Related Tags

no comments yet but open for them

Post a Reply

Your email address will not be published. Required fields are marked *