Encountering a "Uncaught TypeError: Cannot read property 'render' of undefined" error in Three.js when using an object literal

I've been working on converting my code to object literal style. While I was able to successfully create the scene, I'm encountering some issues with the animation.

One specific error message that I'm getting is "Uncaught TypeError: Cannot read property 'render' of undefined" for this line of code:

this.renderer.render(this.scene, this.camera);

Below is the object I have created:

var customThree = {
    objects: function() {
        /*objects*/
    },
    createScene: function() {
        this.container = document.getElementById("container");

        this.scene = new THREE.Scene();

        this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.001, (26 * 10));
        this.camera.position.set(26, (26 / 2), 26);

        window.addEventListener("resize", function() {
            this.camera.aspect = window.innerWidth / window.innerHeight;
            this.camera.updateProjectionMatrix();
            this.renderer.setSize(window.innerWidth, window.innerHeight);
        });

        this.objects();

        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.container.appendChild(this.renderer.domElement);

        this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
    },
    animate: function() {
        this.renderer.render(this.scene, this.camera);
        requestAnimationFrame(this.animate);
    },
    render: function() {
        this.createScene();
        this.animate();
    }
};

customThree.render();

Answer №1

Take a look at my modified example (I decided to use your objects function to render a cube, just for the fun of it:))

Essentially, you have to ensure that you pass the context along with your animate method by utilizing the Function.prototype.bind

requestAnimationFrame(this.animate.bind(this));

What's happening behind the scenes is that the initial call of

this.renderer.render(this.scene, this.camera);
works smoothly without any issues because the context is carried over with the call to this.animate(); method. However, when animate is subsequently called by the requestAnimationFrame method, the context isn't preserved. Therefore, manual passing of the context is necessary.

var three = {
    objects: function() {
        /*objects*/
        var geometry = new THREE.BoxBufferGeometry( 3, 3, 3 );
var material = new THREE.MeshBasicMaterial( { color: 0xffaa00 } );
this.mesh = new THREE.Mesh( geometry, material );
        this.mesh.position.set(24, 14, 12);
this.scene.add( this.mesh );
    },
    createScene: function() {
        this.container = document.getElementById("container");

        this.scene = new THREE.Scene();

        this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.001, (26 * 10));
        this.camera.position.set(26, (26 / 2), 26);

        window.addEventListener("resize", function() {
            this.camera.aspect = window.innerWidth / window.innerHeight;
            this.camera.updateProjectionMatrix();
            this.renderer.setSize(window.innerWidth, window.innerHeight);
        }.bind(this));

        this.objects();

        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.container.appendChild(this.renderer.domElement);
    },
    animate: function() {
        this.mesh.rotation.x += 0.005;
this.mesh.rotation.y += 0.01;

        this.renderer.render(this.scene, this.camera);
        requestAnimationFrame(this.animate.bind(this));
    },
    render: function() {
        this.createScene();
        this.animate();
    }
};

three.render();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js"></script>

<div id="container"></div>

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

Tips for transitioning the li class from active to none

Struggling with changing the li class (of Home) from 'active' to none (or another class) when clicking on the profile tab, and then changing the li class (of Profile) from none to 'active' when the profile is activated. Snippet of my c ...

Showcasing the time variance using javascript/jquery

I am currently using a datepicker to select dates, with the intention of calculating the difference between the chosen dates and then displaying an alert with the calculated difference. Unfortunately, I am encountering issues with getting the code to work ...

Retrieve information from Angular service's HTTP response

Calling all Angular/Javascript aficionados! I need some help with a service that makes API calls to fetch data: app.service("GetDivision", ["$http", function($http){ this.division = function(divisionNumber){ $http.post("/api/division", {division:di ...

Prisma auto-generating types that were not declared in my code

When working with a many-to-many relationship between Post and Upload in Prisma, I encountered an issue where Prisma was assigning the type 'never' to upload.posts. This prevented me from querying the relationship I needed. It seems unclear why P ...

Having trouble with integrating Firebase and Vue database

While attempting to integrate Firebase with my Vue 4 application, I encountered the following error: Uncaught TypeError: db__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function The versions I am using are: "firebase": "^9.0.0&qu ...

Leveraging JavaScript code repeatedly

Apologies if this question has been asked before, as I couldn't find it. I have an HTML table with images used as buttons: <td> <button class="trigger"> <img src="D:\Elly Research\ CO2858\Presentation\Calypso ...

How can I delete an item from an array when I click on a selected element using Material React Select Multiple?

I found this helpful CodeSandBox demonstration that walks through how to implement a multiple material select feature. Here is an array containing all the available options: const permissionsGroupList = [ { name: 'Sellers' }, { name: &a ...

Dealing with the hAxis number/string dilemma in Google Charts (Working with Jquery ajax JSON data)

My Objective I am attempting to display data from a MySQL database in a "ComboChart" using Google Charts. To achieve this, I followed a tutorial, made some modifications, and ended up with the code provided at the bottom of this post. Current Behavior T ...

Retrieving data from a JSON file at 10-minute intervals with Ajax and visualizing it on Google's globe API

After downloading Armsglobe, a globe API provided by Google to draw lines in countries using their names, I noticed that the original code does not fetch JSON data periodically. I attempted to use a simple setTimeout() function in dataloading.js to address ...

Is npm create-react-app giving you trouble?

When attempting to create a React app using the command npm create-react-app appname, the tool would just return me to the same line to input more code. I also gave npx a try, but encountered some errors in the process. See this screenshot for reference: ...

Why is there a false positive in the onChange event for the number type in React TypeScript?

I encountered an error on line 24 Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345) This issue occurred while working with TypeScript for a React experiment. const App: React.FC = () => ...

The custom filter in AngularJS fails to activate when a click event occurs

I am trying to customize the filtering of my table data based on selected conditions from a dropdown menu. I have created an AngularJS custom filter and passed all the necessary parameters. The desired functionality is that if no conditions are selected, ...

Customizing the toString method within an object's definition

There was a question asked previously regarding the overriding of toString. Here is the answer provided: function Foo() {} Foo.prototype.toString = function() { return "this is Foo"; } However, my question is: Is it possible to include this prototy ...

The combination of NextAuth.js and Auth0 seems to be causing an issue with offline_access breaking

I am currently integrating next-auth with the Auth0 provider into an existing application. Everything is functioning properly, however, when attempting to include the offline_access scope in order to retrieve a refresh token, the application randomly crash ...

When attempting to compress JavaScript with uglify-js, an unexpected token error occurs with the symbol ($)

When attempting to compress Bootstrap 4 js file using uglify-js, I encountered an error. The error message reads as follows: "Parse error at src\bootstrap\alert.js:1,7 import $ from 'jquery' ERROR: Unexpected token: name ($)". Now I am ...

The data provided was deemed invalid with the message, "Requested quantity is unavailable," involving NextJS and Commerce JS

Hey there! I'm currently working on setting up an online store using CommerceJs and NextJS, but I've encountered an issue when processing payments. The error message I'm receiving is: "The given data was invalid." "type: unprocessable_entit ...

Using Socket.emit in Ionic may not function as expected

Currently, I'm in the process of establishing a socket connection between my Ionic application and a socket server that I've constructed. The socket connection seems to encounter issues specifically when running the app on an iOS simulator u ...

ReactJS allows for the use of immutable values while still being able to

In my current project, I have predefined values for yearOfEnforcementProceesdings + cityOfEnforcementProceedings. Additionally, there is a serialNumber input field that requires user input. The goal is to display two more unaltered values whenever the seri ...

Unable to display content on the ejs file

Currently, I have been diving into the world of node.js and exploring how to manipulate data by writing and reading from JSON files. It has been an interesting journey so far; however, I encountered a hiccup. Specifically, when attempting to post new data ...

Step-by-step guide on implementing a fade effect to a specific JavaScript element ID

When I click a button, the image on the screen disappears. I am looking to add a fade effect to this action. Can someone help me achieve this using CSS? #hide{-webkit-transition: all 1s ease-in-out;} For reference, here is a demo showcasing the current b ...