Error: The OrbitControls function is not recognized in THREE.JS

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const controls = new OrbitControls(camera);
camera.position.set(200, 0, 0);
controls.update();

const geometry = new THREE.SphereGeometry(50, 32, 32);
const material = new THREE.MeshBasicMaterial({
  color: 0xffff00
});
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);


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

function animate() {

  requestAnimationFrame(animate);

  controls.update();

  renderer.render(scene, camera);

}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c3dfc5d2d2f7879986858e9987">[email protected]</a>/build/three.min.js"></script>

Upon running my JavaScript code, I encountered the error message "Uncaught ReferenceError: OrbitControls is not defined". I came across a relevant discussion on this issue, but it did not provide a solution. Do you have any suggestions?

It's worth noting that my OrbitControls.js file is located within the same directory as the three.js file.

Answer №1

Your code now runs smoothly without any errors after making a few adjustments. One change I made was importing OrbitControls and defining the renderer at the beginning, then passing it into OrbitControls.

Additionally, I included a second snippet inspired by a three.js example from their website. This snippet should create the desired yellow sphere in your project.

let camera, controls, scene, renderer;

init();
//render(); // remove when using next line for animation loop (requestAnimationFrame)
animate();

function init() {

  scene = new THREE.Scene();
  scene.background = new THREE.Color(0xcccccc);
  scene.fog = new THREE.FogExp2(0xcccccc, 0.002);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
  camera.position.set(400, 200, 0);

  // controls

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

  //controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)

  controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
  controls.dampingFactor = 0.05;

  controls.screenSpacePanning = false;

  controls.minDistance = 100;
  controls.maxDistance = 500;

  controls.maxPolarAngle = Math.PI / 2;

  // world

  const geometry = new THREE.SphereGeometry(50, 32, 32);
  const material = new THREE.MeshBasicMaterial({
    color: 0xffff00
  });
  const sphere = new THREE.Mesh(geometry, material);
  scene.add(sphere);




  //

  window.addEventListener('resize', onWindowResize);

}

function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);

}

function animate() {

  requestAnimationFrame(animate);

  controls.update(); // only required if controls.enableDamping = true, or if controls.autoRotate = true

  render();

}

function render() {

  renderer.render(scene, camera);

}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e3978b918686a3d3cdd2d1d1cdd3">[email protected]</a>/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfabb7adbaba9feff1eeededf1ef">[email protected]</a>/examples/js/controls/OrbitControls.min.js"></script>

let camera, controls, scene, renderer;

init();
//render(); // remove when using next line for animation loop (requestAnimationFrame)
animate();

function init() {

  scene = new THREE.Scene();
  scene.background = new THREE.Color(0xcccccc);
  scene.fog = new THREE.FogExp2(0xcccccc, 0.002);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
  camera.position.set(400, 200, 0);

  // controls

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

  //controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)

  controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
  controls.dampingFactor = 0.05;

  controls.screenSpacePanning = false;

  controls.minDistance = 100;
  controls.maxDistance = 500;

  controls.maxPolarAngle = Math.PI / 2;

  // world

  const geometry = new THREE.SphereGeometry(50, 32, 32);
  const material = new THREE.MeshBasicMaterial({
    color: 0xffff00
  });
  const sphere = new THREE.Mesh(geometry, material);
  scene.add(sphere);




  //

  window.addEventListener('resize', onWindowResize);

}

function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);

}

function animate() {

  requestAnimationFrame(animate);

  controls.update(); // only required if controls.enableDamping = true, or if controls.autoRotate = true

  render();

}

function render() {

  renderer.render(scene, camera);

}
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffbe7fdeaeacfbfa1bebdbda1bf">[email protected]</a>/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f88c908a9d9db8c8d6c9cacad6c8">[email protected]</a>/examples/js/controls/OrbitControls.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to manipulate arrays using React hooks?

Struggling with updating arrays using hooks for state management has been quite a challenge for me. I've experimented with various solutions, but the useReducer method paired with dispatch on onClick handlers seems to be the most effective for perform ...

Live Edit API

Currently, I am developing an application that requires near real-time collaborative editing capabilities for documents, similar to the functionality found in Google Documents. Since I am a beginner in this area, I would greatly appreciate any information ...

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...

Is it possible for a dash in a GET variable name to cause issues with req.query in NodeJS Express?

I am currently developing a GET endpoint in Node.js using Express to handle the following variable: ?message-timestamp=2012-08-19+20%3A38%3A23 However, I am facing difficulty accessing it through req.query. Whenever I try to access req.query.message-time ...

Exploring the wonders of useState in React/JavaScript - a comprehensive guide

I encountered an issue while attempting to map an API request from a useState hook. The fetch operation functions correctly and returns an array of objects that I then assign to my useState variable. Subsequently, when I try to map over the useState varia ...

Sorting a select element using Javascript/JQuery while taking into consideration the label attribute present in the options

It came to my attention that the jQuery options and examples only covered the text and value attributes, causing errors when attempting to add the label attribute. I am looking for a way to include the label attribute in the sorting process, especially whe ...

Issue arises when trying to implement sidebar navigation in Angular with Materialize CSS

Just starting my Angular journey and running into some trouble trying to set up a practical and responsive menu using SidebarNav and Dropdown. I used CLI to install and configure angular2-materialize and materialize-css. To create the menu, I made a comp ...

When attempting to insert data retrieved from axios into a table within a React component, the data is coming back as

Hi there! Currently, I'm in the process of developing an application that retrieves data from an API and my goal is to display it in a Material UI Table within a React environment. Strange issue I'm encountering: when I use console.log to check ...

Enhancing the appearance of specific text in React/Next.js using custom styling

I have a table and I am currently working on implementing a search functionality that searches for an element and highlights the search terms as they are entered into the search bar. The search function is functional, but I am having trouble with the highl ...

Exploring the depths of AngularJS through manual injection

I seem to have misunderstood the tutorial and am struggling to get manual injection working on my project. As I'm preparing to minify and mangle my JS code, I decided to manually inject all my modules and controllers. However, I keep encountering err ...

Dynamic jQuery backstretch feature: automatic image cycling and reversing

I am currently using backstretch on my website and attempting to create a continuous loop of the moving image by automatically shifting it from left to right and back. However, I am facing difficulties as the background only moves in one direction. I am se ...

Leveraging the Railway Pathway from the Google Maps API

I need to customize my map to display only railway stations instead of the entire map. How can I achieve this? Below is the code I have attempted: <html> <head> <style type="text/css"> html { height: 100% } ...

Enhancing Bootstrap UI Typeahead to Display Multiple Fields in Results List

Having encountered the same issue as described in this question: Bootstrap-UI Typeahead display more than one property in results list? I made adjustments to the Plunker provided in the answer to fit my requirements: http://plnkr.co/edit/FdkvCUUD3ob7dt2 ...

Experiencing difficulties launching my Server.JS due to a listening error

Hey there, I'm struggling to get my server.js up and running. Whenever I try to run node on it, I keep getting the error message "listening on *:3000". Below is the code for my server.js: var app = require('express')(); var http = require(&a ...

The visibility of buttons can be controlled based on the selected radio option

I have just completed setting up 4 buttons (add, edit, delete, cancel) and a table that displays data received via ajax. Each row in the table contains a radio button identified by the name "myRadio". When a radio button is clicked, I need the buttons to ...

Issues with Cordova and JQuery ajax functionality not operating as expected

I am facing an issue with implementing AJAX functionality in my Cordova app (CLI 6.3.1) on Visual Studio 2017. It works fine on the emulator, but I encounter a connection error when installing it on a mobile phone. I have already included CSP as shown bel ...

Is there a way to transform the SmartyStreets' jQuery.LiveAddress plugin into its JavaScript SDK?

My website currently utilizes the jQuery.LiveAddress plugin, however, it was deprecated and subsequently removed by SmartyStreets back in 2014. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <s ...

Display additional tiles within a compact container

I'm attempting to replicate the user interface used by foursquare! Positioning the map slightly off center like they have . I've figured out how to do one part but struggling with the second part. Initially, I loaded the map in a small div (t ...

`Storing modified PDF containing interactive form elements using integrated Chrome viewer and transferring it to a remote server`

Our current setup utilizes the default embedded Chrome PDF viewer to showcase a PDF document with interactive form fields, enabling users to conveniently fill out the form. Once completed, they can click on the download button to save the form with or with ...

Deliver search findings that are determined by matching criteria, rather than by identification numbers

I am seeking to return a JSON match upon form submission, rather than simply searching for a specific ID. However, I am uncertain about how to structure this. I have the ability to search for the necessary match in a JavaScript document within one of my n ...