11/13

7.2. Camera control

So far, the 3D scene is displayed from a single point of view. It is usually convenient to be able to change the viewpoint interactively.

Three.js proposes different extension to control the camera (rotation, pan, zoom, etc) using a mouse. A common control system is OrbitControls.

OrbitControls is not directly accessible from three.js library and should be loaded as a JavaScript script separately (source code).

The code from directory 01_orbit_controls uses OrbitControls to handle the camera interactively.

[webpage, src, js]

  • Left mouse drag and drop: rotation

  • Right mouse drag and drop: pan

  • Mouse scrool: zoom


  • Observe that the JavaScript code corresponding to OrbitControls is loaded in the HTML file - after Three.js library, and before the code of the 3D scene -

    <script src="lib/three.min.js" defer></script>
    <script src="lib/OrbitControls.js" defer></script>
    <script src="scene.js" defer></script>
  • The use of the control in the JavaScript code contains two steps

    • An initialization from the camera to be performed once

        sceneElements.control = new THREE.OrbitControls( camera );
        sceneElements.control.screenSpacePanning = true;
  • The update of the control to be called at every frame

        sceneElements.control.update();
  • When moving the camera below the plane, you may observe artifacts at the contact surface between the plane and the other shapes. This effect called Z-Fighting is linked to the limited precision of the so-called Z-Buffer used to define which part of an object should be drawn in front of the other. In this case, two objects have the same position at the floating precision, and leads to visual artifacts.
    To limit such artifact, some objects can be offseted by a small value in order to avoid contact surfaces.