Error in Three.js: Trying to Call Undefined Function

I keep encountering the

Uncaught TypeError: undefined is not a function
error while working with Three.js. This error is specifically being shown at the line where I'm creating a THREE.PerspectiveCamera. Here's the script:

window.requestAnimFrame = (function(callback){
        return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback){
            window.setTimeout(callback, 1000 / 60);
        };
    })();

    function animate(lastTime, angularSpeed, three){
        // update
        var date = new Date();
        var time = date.getTime();
        lastTime = time;

        // render
        three.renderer.render(three.scene, three.camera);

        // request new frame
        requestAnimFrame(function(){
            animate(lastTime, angularSpeed, three);
        });
    }

    $(window).bind('load',function(){
        var angularSpeed = 0.2; // revolutions per second
        var lastTime = 0;
        $container = $("#container");
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        $container.append(renderer.domElement);

        // camera - Uncaught Type Error on the below line
        var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
        camera.position.y = -450;
        camera.position.z = 400;
        camera.rotation.x = 45 * (Math.PI / 180);

        // scene
        var scene = new THREE.Scene();

        var material = new THREE.LineBasicMaterial({
                            color: 0x0000ff,
                        });
        var geometry = new THREE.Geometry();
        for(var i=0;i<100;i++){
            geometry.vertices.push(new THREE.Vector3(i-100,i-100,i-100));
            geometry.vertices.push(new THREE.Vector3(i+100,i+100,i+100));
            var line = new Three.Line(geometry,material);
            scene.add(line);
            geometry=new THREE.Geometry();
        }


        // create wrapper object that contains three.js objects
        var three = {
            renderer: renderer,
            camera: camera,
            scene: scene,
        };

        animate(lastTime, angularSpeed, three);
    });

Could the issue be related to how I am declaring the camera? I've gone through the documentation provided by three.js and my code seems quite similar to their example. Any suggestions would be greatly appreciated.

UPDATE: Initially, I was using a local copy of Three.js which led to the PerspectiveCamera error. Upon switching it with the external link , the PerspectiveCamera error disappeared but now a new error has surfaced within the Three.js script. The error message reads

Uncaught TypeError: Cannot read property 'x' of undefined
on line 337 of the Three.js script.

Thank you.

Answer №1

The issue with your local copy is that you included the unbuilt Three.js file (located in src/Three.js) instead of the correct files which are build/three.js or build/three.min.js. I resolved this problem by replacing the incorrect file with one of the build files and updating the reference in the script tag's src attribute, after which everything worked smoothly.

To simplify:

mrdoob-three.js-2524525(or a different number)
 |
 +----build
 |     |
 |     +--three.js     <-- YES, CORRECT FILE
 |     +--three.min.js <-- YES
 |     ...
 |
 +----src
 ...   |
       +--Three.js     <-- NO, PREBUILT FILE CONTAINING ONLY CONSTANTS
       ...

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

Why is Bootbox's dialog.modal('hide') not hiding the modal window?

I am facing an issue with bootbox.js modals. When the code is executed and waiting for a response, the readyState changes to 3 and the modal will show. However, after the request is complete and the ready state changes to 4, "readystate 4" is printed in ...

Utilizing jQuery's slice() and remove() functions, followed by triggering jQuery's isotope to reorganize

I have been working on a project for the website My goal is to display only 25 posts and rearrange the post divs (.dcsns-li) by calling Isotope again. Here is the code I am using: jQuery(window).load(function(){ var nPosts = jQuery(".dcsns-li").length ...

What is the process for assigning the value returned from an Angular HTTP request to ng-bind?

I am trying to retrieve a value from an HTTP request in AngularJS and set it as the result in a variable that is bound to ng-bind. The goal is for the value returned from the HTTP request to be displayed when text is typed into an input field. Below is th ...

Analyzing JavaScript code coverage through unit testing with Jenkins and SonarQube

We have successfully implemented Jenkins/SonarQube to enforce a requirement that any new code committed by developers must have at least 70% unit test code coverage for Java. However, when it comes to applying the same rule for JavaScript, we encountered s ...

Property referencing for change detection is a valuable technique

I'm struggling to update my template when changing a boolean property that is referenced in another array property. I expected the changes to reflect in my template, but they are not showing up. Upon initial load, everything appears in its initial st ...

Utilize selenium IDE to retrieve a specific portion of text and save it as a variable

I am trying to figure out how to extract the number 694575 from a text using Selenium Ide and store it in a variable for future use. Here is the text I am working with: <div class="loginBoxTitle">Edit Exhibition Centre - 694575, Exhibition Center1&l ...

How can I manipulate JSON animation using Three.js?

I utilized this code to import a JSON animation from Blender: var loader = new THREE.JSONLoader(); loader.load( 'monster2.json', function ( geometry, materials ) { var material = materials[ 0 ]; material.morphTargets = true; ...

Adding a personalized service into a separate service within Angular 2

I am having trouble injecting my own service into another service. While I can inject standard Angular services like Http without any issues, attempting to inject custom services results in an exception. For example, here is how MyService is set up: impo ...

Create an AngularJS task manager that saves your to-do list even when the page is refreshed

Currently, I am developing a straightforward to-do list application using AngularJS within an ASP.NET MVC template. Surprisingly, I have successfully integrated Angular and Bootstrap to achieve the desired functionality. The app allows users to add and re ...

Ways to exit the current browser window?

Is there a way to close the current browser window using JavaScript or another language that supports this functionality? I've tried using the window.close() function, but it seems to only work for windows opened with window.open(). Thank you in adv ...

Managing JavaScript promise rejections

What is the best approach to managing an error, such as the one labeled "new error" in the code snippet below, that occurs outside of a promise? function testError() { throw new Error("new error") // How can this error be properly handled? var p ...

javascript array push not functioning as expected

I have written some JavaScript code that is supposed to add another element with a value of 1 when I click a button. However, currently it is resetting the array so only one element gets added each time. How can I fix this issue? var x = document.getElem ...

What is the best way to send the link's ID to an AngularJS controller?

I have a scenario similar to the following: <a href="#" title="Post 1" id="car1"> Audi car </a> <a href="#" title="Post 1" id="car2"> BMW car </a> How can I pass the ID to the controller? I attempted the following: <a href= ...

What is the process for accessing a URL using a web browser and receiving a plain text file instead of HTML code?

Hello there! I've created a simple HTML file located at that can display your public IP address. If you take a look at the code of the page, you'll notice that it's just plain HTML - nothing fancy! However, I'm aiming for something mo ...

Having trouble accessing the value of an item in a dropdown box on a website

I am currently developing a webpage using HTML5 and Knockout Js. I am facing an issue where I am unable to retrieve the ID of the selected item from a dropdown box in order to insert a value into an SQL table. As an example, consider the following SQL tab ...

Is it possible to store Socket.IO responses in a cache for quicker retrieval?

Consider this scenario where I have a websocket implementation shown below: let itemsArray = []; function fetchData() { itemsArray = await db.query(`SELECT * FROM Items`); } function emitData() { io.sockets.in("room_foo").emit("data", JSON.stringify ...

Convert a list to a JSON object utilizing the Json.NET library

I am using json.net to convert currency rates to JSON format. In the C# entity, there are Name and Value properties; where Name represents currencies like USD, GBP, etc. and Value holds the currency rate. Since I do not know the index of different curren ...

Determine if the user's intention is to tap or to scroll up and down the page on a touch-sensitive device

When a user taps outside of a popup-div (touchstart), the popup should be hidden. However, if the user's intention is to scroll/swipe (touchmove), the popup should not be hidden. Can you provide a code example that can detect and handle these two ac ...

Determining the best time to utilize AngularJS data binding compared to Rails data binding depends on the

Combining Rails and AngularJS appears to be a promising combination. However, I find myself struggling with the concept of data binding. In AngularJS, data is provided through a scope which then generates content based on that data. On the other hand, my ...

"Utilizing Javascript's Regex to selectively replace only the first character

Forgive me if this is a beginner question, but I'm really unsure about this. Is there a regex solution to replace a character that appears first in a string? For example: 12 13 14 15 51 41 31 21 All data where '1' is the first character s ...