Error rotating the camera in Three.js

I can't figure out why Firebug keeps throwing an error that says "THREE is not defined" for my var camera. It's confusing because I clearly see the THREE declaration on the right side of the equals sign.

        init();
        animate();

        function init()
        {
            var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
            camera.position.z = 500;

            var controls = new THREE.TrackballControls( camera );
            controls.addEventListener('change', render);

            var scene = new THREE.Scene();

            var geometry = new THREE.BoxGeometry(100, 100, 100);
            var material = new THREE.MeshBasicMaterial();

            var mesh = new THREE.Mesh( geometry, material );
            scene.add(mesh);

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

        function animate()
        {
            requestAnimationFrame( animate );
            controls.update();
        }

        function render()
        {
            renderer.render( scene, camera );
        }

Answer №1

Your implementation looks solid overall, but one potential issue is that you're declaring your variables within the init() function scope. This means they are only accessible within that specific function and not outside of it.

To ensure your variables can be accessed globally throughout your code, consider declaring them outside of any functions. Here's an example:

var camera, controls, scene, geometry, material, mesh, renderer;

init();
animate();

function init() {
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 500;
...

Answer №2

If you're encountering issues, it's possible that the three.js script isn't being included correctly. Use Firebug to monitor the THREE variable - it should be defined before you begin working with THREE.JS. Be sure to check for any network errors related to loading the script.

Additionally, make sure to execute your code after the entire page has finished loading.

window.addEventListener('load', initialize);

This will ensure that the initialize function is only called once the page is fully loaded.

Remember to declare your variables in the global scope rather than inside the init function. Also, don't overlook calling the render function within your animate function.

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

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Cel shading effect plugin for three.js for creating a comic book style in real time simulation

Is it possible to create a cel shading, comicbook effect in three.js similar to the example provided? Can you point me towards any tutorials or sample code for achieving this effect? Example ...

AngularJS - Click event failing to trigger controller function

I am currently honing my skills in Angularjs and Nodejs through working on a project. Following a helpful tutorial, I have structured my folders and configured my routes. Issue: I implemented a method called isActive to update ng-class when a tab is ...

Interacting with Socket.io using NodeJS and Express

Presently engaged in developing a Node.JS backend that utilizes both express.js and Socket.io. The core structure of the application is outlined below: var app = require('express')(); var http = require('http').Server(app); var io = re ...

Tips on transforming a JSON file into a response for my personal server

After successfully converting an Excel file to JSON format using my code, I encountered a challenge when trying to convert this as a response. Despite attempting to use res.send in the JS code, it only displayed directory/inner codes instead of a response. ...

The radio button that disables other inputs only functions correctly for a single element when using Query Selector, but does not work with Query

I have attempted to develop a form section that is disabled when the user selects option A and enabled when they choose option B. document.getElementById('delivery').onclick = function() { var disabled = document.querySelectorAll(".dis ...

Generate a list of keys along with an array containing sets of values

In my thesaurus app, users can enter a base word like "dog" and its synonyms like "canine, hound, mutt." Once entered, these words are stored in a database. However, to streamline the process and avoid multiple form submissions, I want to create simultaneo ...

Is there a way to cycle through each element within a loop and output a corresponding item from another array?

My data structure consists of an array of objects like this: arrOfObjs = [{type: "flower", egg: "something"}, {type: "flower", egg: "something2"}, {type: "notFlower", egg: "something3"}, {type: &q ...

Angular HTML is throwing an error related to object arrays

Is there a way to display only specific fields of an array? <div class="form-check" *ngFor="let periodo of filterPeriodos()"> <div>{{periodo.periodos | json}}</div> <input class="form-check-input mr- ...

The encodeURIComponent function does not provide an encoded URI as an output

Looking to develop a bookmarklet that adds the current page's URL to a specific pre-set URL. javascript:(function(){location.href='example.com/u='+encodeURIComponent(location.href)}()); Even though when I double encode the returned URL usin ...

Navigating between components in angular2 modules: A tutorial

Currently, I am utilizing angular2 Final version for my development tasks. Within my project, I have established 3 distinct modules: AppModule ProjectModule DesignerModule In the past, I solely had AppModule which integrated the following RoutingModule ...

Leveraging Angular Dragula without the need for RequireJS

I'm eager to incorporate Drag and Drop functionality into my Angular project with the help of the angular-dragula module (https://github.com/bevacqua/angular-dragula). However, it appears that this module heavily relies on RequireJS. My experience wit ...

Is there a way to simplify and optimize the code further?

Here is the code snippet from my index.blade.php: HTML @foreach($sesis as $sesi) <td>{{ $sesi->waktu }} <label class="switch switch-text switch-info switch-pill" id="label-switch{{ $sesi->id } ...

Explanation requested for previous response about returning ajax data to the parent function

After coming across a helpful answer in the question titled How do I return the response from an asynchronous call?, I attempted to implement it without success. Reviewing Hemant Bavle's answer (currently with 62 votes) gave me hope, but my implement ...

I encountered an issue while trying to use jshint with a simple hello world script, receiving the error message: "line 0, col 0, Bad option: 'script'."

This is a basic introduction to my coding journey. function greet() { return 'Hello world'; } Here is the jshint setup I am using: { "browser": true, "browserify": true, "devel": true, "script" ...

What is the best way to retrieve the dimensions of a custom pop-up window from the user?

Currently, I am in the process of developing a website that allows users to input width and height parameters within an HTML file. The idea is to use JavaScript to take these user inputs and generate a pop-up window of a custom size based on the values pro ...

Showcasing JSON information on an HTML webpage depending on the URL parameters provided

I am attempting to achieve the following using HTML and Javascript exclusively. Once users submit my form, their data is added to a confirmation page in this format: On that page, I aim to display all locations from locations.json with a country matching ...

How exactly does this JavaScript code determine the index of the maximum value within an array?

Examining the specific line of code: let largest = arr.reduce((a,v,i) => v > a[1] ? [i,v] : a, [-1,0]); I find this part a, [-1,0] particularly perplexing, as I am unsure of its syntax. How does a function before the comma? ...

How come my dimensions are not returning correctly when I use offset().top and scrollTop() inside a scrolling element?

Currently in the process of developing a web app at , I am looking to implement a feature that will fade elements in and out as they enter and leave the visible part of a scrolling parent element. Taking inspiration from myfunkyside's response on this ...

What is the best way to divide a library and its plugins into separate npm packages?

I am currently developing a JavaScript library that allows users to select specific plugins to add to their project along with the main library. However, I am facing some challenges with modules and webpack. To illustrate how the code is structured, I am w ...