The error "Uncaught TypeError: Cannot read property 'render' of undefined" occurs when using Three.js along with OrbitControls

I am having an issue with my rotating cube class. Whenever I try to rotate or zoom the cube, I encounter an error message saying "Cannot read property 'render' of undefined". I suspect that the problem lies within the scopes. Below is my class implementation:

myRotationClass = function() {
    this.camera = null;
    this.scene = null;
    this.renderer = null;
    this.cube = null;

    this.initialize = function(container) {
        this.scene = new THREE.Scene();
        this.camera = setupCamera();
        this.cube = createCube();
        this.scene.add(this.cube);
        this.setupRenderer();
        this.setupControls();
        container.appendChild(this.renderer.domElement);
        this.animateRotation();
    };

    function setupCamera() {
        var camera = new THREE.PerspectiveCamera(20, 300 / 400, 1, 10000);
        camera.position.z = 1800;
        return camera;
    }

    function createCube() {
        var geometry = new THREE.BoxGeometry(300, 200, 200);
        var materials = ...;

        var cube = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        return cube;
    }

    this.setupRenderer = function() {
        this.renderer = new THREE.WebGLRenderer({antialias: true});
        this.renderer.setClearColor(0xffffff);
        this.renderer.setSize(this.sceneWidth, this.sceneHeight);
    };

    this.setupControls = function() {
        this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
        this.controls.addEventListener('change', this.renderCube);
    };

    this.animateRotation = function() {
        requestAnimationFrame(this.animateRotation.bind(this));
        this.renderCube();
    };

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

Thank you.

Answer №1

There seems to be a scoping issue with the callback function specified in this code snippet:

this.controls.addEventListener( 'change', this.render );

To resolve this, declare a variable named scope in your class:

var scope = this;

Then, modify your render() method as follows:

this.render = function () {

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

};

It is important to note that the event listener is added to stop the animation loop.

Therefore, remove the loop and render only when the camera is moved by the mouse.

Don't forget to call render() initially and after loading models.

Using three.js version r.69

Answer №2

One way to maintain the scope for the render method is by using the bind method like shown below:

this.controls.addEventListener( 'change', this.render.bind(this) );

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 implement a Cascading Async Select feature using @atlaskit/select library?

I recently delved into React and I'm currently exploring how to create a Cascading Async Select (for example, selecting Country then City) using @atlaskit/select. As per the documentation, I utilized the option loadOptions in the initial Async Select ...

Struggling with a character entity in Javascript? Learn how to escape it and avoid any display issues (such as showing

document.title = ("welcome → farewell"); Trying to display the arrow symbol "→" but it's not showing correctly. Any tips on how to properly escape it? ...

Maximizing the power of datatables with ajax integration

Exploring pagination with AJAX on datatables.net is something I want to try. I have two input fields where users can enter start and end dates, followed by the table structure below: <table class="table table-hover" id="example"> < ...

Issue with Bootstrap 4 Navbar collapsing and not expanding again

Help needed! My navigation bar collapses when the window is resized, but clicking on the hamburger icon does not open it back up. I have included my code below. Can someone please provide guidance on how to expand the collapsed navbar? <html lang=&quo ...

What is the best way to extract an object by its specific id using json-server?

I am attempting to retrieve an object by its id using json-server. If I only return a single variable (one JSON) in the module.exports of the database file, everything works fine. However, if I try to return an object with multiple variables, I encounter a ...

An error was encountered: "Uncaught SyntaxError: Unable to utilize import statement outside of a module in

I have come across the following code while learning React and trying to execute it. HTML <html> <head> <link href="index.css" rel="stylesheet"> </head> <body> <div id="r ...

Challenge with Updating React Components When Switching Themes

In my React application, I'm facing a challenge with theme switching. There are two themes available: Theme One and Theme Two. To dynamically load theme components, lazy loading has been implemented based on the selected theme. Each theme has its own ...

Exploring the feature of setting the checked state in Radio.Group using Antd

I am dealing with dynamic data that needs to be displayed in a radio button format. One of the challenges is comparing the dynamically generated id with the active radio id and setting it as checked using Radio.Group. Unfortunately, the current code is no ...

Create a dynamic and interactive website using a combination of jQuery and AngularJS

I recently came across an interesting tidbit on the FAQs of Angular stating that "Angular can use jQuery if it's present in your app when the application is being bootstrapped". This got me thinking, is it considered a best practice to include both j ...

Transferring information from AJAX to PHP script with the click of a button

Simply put, I am in the process of adding a pop-up update panel to my to-do website using an HTML button. The website already has a login-register system and uses MySQL queries to display different tables for each user. The update buttons on the website c ...

What is the best way to get a string as a return value from an async function that uses the request API

I'm currently working on a project that involves printing the HTML code source as a string using the request API. I've created a function to fetch the data as a string, but when I try to print the output, it returns undefined. I'm struggling ...

Adjust the size of the logo as the user scrolls

Currently, I am implementing a JavaScript feature that allows my logo to shrink when the user scrolls down and grow when they scroll up. To achieve this effect, I am utilizing the jQuery functions addClass and removeClass. However, I have encountered som ...

Supporting server-side routing with NodeJS and Express for AngularJS applications

My current setup includes NodeJS + expressJS on the server and AngularJS on the client side. The routes defined in my AngularJS controller are as follows: app.config(function($routeProvider,$locationProvider) { $routeProvider .when('/field1/:id&apo ...

Display only the offcanvas button

Having trouble with Bootstrap 5 offcanvas? The offcanvas doesn't hide when I click the button again. <button data-bs-toggle="offcanvas" role="button">Add to Cart</button> Every time I click the button again, the offcan ...

Conceal and reveal buttons at the same location on an HTML webpage

There are 3 buttons on my custom page called page.php: <input type="submit" value="Btn 1" id="btn1"> <input type="submit" value="Btn 2" id="btn2" onClick="action();> <input type="submit" value="Btn 3" id="btn3" onClick="action();> ...

Clicking on a link initiates the dropdown menu for selecting an option

This project is specifically designed for mobile use, so there's no need to worry about how it will appear on desktop screens. In this project, I have an "a href" with an icon next to it that simulates a button. When a user clicks on it, a dropdown me ...

Trigger a click event in jQuery to activate a form through a hyperlink

I'm facing an issue where I want to implement a password-reset form based on a certain flag being triggered. Currently, my code is set up to prompt the user to change their password if the password_changed_flag is not present. Depending on the user&ap ...

A platform for creating ER and flow diagrams specifically tailored for web applications, utilizing open source software

Our team is currently working on creating a web application that enables users to create diagrams, such as flow or ER diagrams. We are looking for ways to convert these diagrams into XML or other formats for representation. Are there any open-source soft ...

Utilize local .json data within a React component

Here is a snippet from my local .json file: { "results": [ { "id": 1, "title": "2 bedroom apartment to rent", "location": "30 South Colonnade London E14 5EZ", "description": "The building offers a communal lifestyle which co ...

Steps to update XmlHttpRequest URL during image upload

I am currently facing an issue with updating images on my website. When I try to update an image, it redirects to the wrong URL instead of the intended one. The form is set to post data to this URL: POST http://127.0.0.1/mgt/upload/processImage/foodImage ...