11

I am trying to add Orbit Controls to my scene without success. The code below keeps giving me an error Uncaught TypeError: THREE.OrbitControls is not a constructor. I have tried different solutions I came across the web but, the error still persists. What am I doing wrong?

Pseudocode

  • Add Orbit Controls
  • Be able to use Orbit Controls in the scene

Thank you in advance.

Codepen

HTML

<html>
    <head>
        <title>My first three.js app</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
    </head>
    <body>
        <script src="js/three.js"></script>
    <script src="https://82mou.github.io/threejs/js/OrbitControls.js"></script>
    </body>
</html>

JS

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var scene = new THREE.Scene();

// var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

// var renderer = new THREE.WebGLRenderer();
// renderer.setSize( window.innerWidth, window.innerHeight );
// document.body.appendChild( renderer.domElement );

// CAMERA
var camera = new THREE.PerspectiveCamera(75, 320 / 240, 1, 1000);
camera.position.set(250, 200, 250);
camera.lookAt(0, 0, 0);

// add controls for the camera
var controls = new THREE.OrbitControls(camera);



var geometry = new THREE.PlaneGeometry(100, 50);
var material = new THREE.MeshBasicMaterial( { color: 0xFFFFFF } );
var plane = new THREE.Mesh( geometry, material );
scene.add( plane );

camera.position.z = 200;

var animate = function () {
  requestAnimationFrame( animate );

    controls.update();

  // plane.rotation.x += 0.01;
  // plane.rotation.y += 0.01;

  renderer.render( scene, camera );

};

animate();
2
  • 1
    It requires 2 arguments var controls = new THREE.OrbitControls(camera, renderer.domElement) Commented Jan 16, 2020 at 12:03
  • Thank you for your reply Blindman67. Still no success though. Commented Jan 16, 2020 at 12:08

1 Answer 1

13

There is an issue in your codepen. When you import OrbitControls via ES6 imports, it's not necessary to use the THREE namespace. So when doing something like this:

import { OrbitControls } from "https://unpkg.com/[email protected]/examples/jsm/controls/OrbitControls.js";

you have to to create OrbitControls like so:

controls = new OrbitControls( camera, renderer.domElement );

Live example: https://jsfiddle.net/68kzagry/1/

Sign up to request clarification or add additional context in comments.

1 Comment

If installed via npm, the correct way to import OrbitControls is thus: import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.