The error message "Uncaught TypeError: Cannot set property 'map' of undefined" occurs when using the callback function to load a texture with Three.js TextureLoader

Currently working with Three.js and aiming to refactor the code. I am looking to create a dedicated class called "Floor" for generating floors:

    import {
        Mesh,
        MeshBasicMaterial,
        PlaneGeometry,
        RepeatWrapping,
        sRGBEncoding
    } from 'three';
    
    export class Floor {
        constructor(textureLoader, pathName) {
            let floorMat;
            const geometry = new PlaneGeometry(1000, 1000, 50, 50);
            geometry.rotateX(-Math.PI / 2);
            const texture = textureLoader.load(pathName, function (map) {
                map.wrapS = RepeatWrapping;
                map.wrapT = RepeatWrapping;
                map.anisotropy = 4;
                map.repeat.set(10, 24);
                map.encoding = sRGBEncoding;
                floorMat.map = map;
                floorMat.needsUpdate = true;
            });
            const material = new MeshBasicMaterial({
                color: 0xffffff,
                map: texture
                // side: DoubleSide,
            });
            this.mesh = new Mesh(geometry, material);
            this.mesh.needsUpdate = true;
            this.mesh.position.y = 0;
        }
    }

This class is then used in my main.js file like so:

    const textureLoader = new TextureLoader();
    const floor = new Floor(textureLoader, "textures/hardwood2_diffuse.jpg");

Although everything seems to be functioning correctly, the browser's console is showing an error message: "Uncaught TypeError: Cannot set property 'map' of undefined". This issue has got me stumped.

#EDIT:

The solution turned out to be as follows:

constructor(textureLoader, pathName) {
        const geometry = new PlaneGeometry(1000, 1000, 50, 50);        
        geometry.rotateX(-Math.PI / 2);
        const texture = textureLoader.load(pathName, function (map) {
            map.wrapS = RepeatWrapping;
            map.wrapT = RepeatWrapping;
            map.anisotropy = 4;
            map.repeat.set(10, 24);
            map.encoding = sRGBEncoding;
            floorMat.map = map;
            floorMat.needsUpdate = true;
        });        
        const floorMat = new MeshBasicMaterial({
            color: 0xffffff,
            map: texture
           
        });        
        this.mesh = new Mesh(geometry, floorMat);
        this.mesh.needsUpdate = true;
        this.mesh.position.y = 0;
    }

Answer №1

There is a error in your code where you declare floorMat without initializing it, resulting in an undefined variable. Additionally, assigning its map property when it's not a material type is incorrect. Also, stating that it needsUpdate even though it has just been initialized is misleading. Lastly, declaring the material variable but ignoring the previously declared floorMat.

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

Objects That Are Interconnected in Typescript

I have been delving into TS and Angular. I initially attempted to update my parent component array with an EventEmitter call. However, I later realized that this was unnecessary because my parent array is linked to my component variables (or so I believe, ...

Is there a way to display one of the divs in sequence each time the page is reloaded?

Is there a way to display the divs sequentially when the page is refreshed? For instance, on the initial load, only div 1 should appear, and with each refresh it should cycle through divs 2, 3, 4, and 5 before starting over. Below is an example I'm c ...

Is the disable feature for React buttons not functioning properly when incorporating Tailwind CSS?

import React, { useState } from "react"; import facebook from "../UI/icons/facebook.png"; import Button from "../UI/Button/Button"; import Card from "../UI/Card/Card"; import twitter f ...

Utilizing Template Styling for Iterating through Lists in Vue.js

I would like the output format to display one player value followed by one monster value, repeating this pattern for each pair of values. new Vue({ el: app, data: { output: { player: [1, 5, 61, 98, 15, 315, 154, 65], monster: [2,14, ...

Refreshing a page following an AJAX request made with jQuery

I am working on a JSP page that shows student details. When a student is selected from the dropdown box, it triggers an onchange event to retrieve the minimum and maximum marks for that student. <form name="listBean"> <c:forEach var="Item" i ...

Combining selected boxes through merging

Looking to create a simple webpage with the following requirements: There should be 10 rows and 3 boxes in each row. If I select 2 or more boxes or drag a box, they should merge together. For example, if my initial screen looks like this: and then I se ...

Tips for optimizing AngularJS performance with large scopes

Currently, I am working on an Angular app for my company and have encountered a major issue. The app has become extremely slow, even after trying to optimize it using techniques like onetimebind and track by. Despite initial improvements, the performance i ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

Audio in A-Frame does not function properly when in VR mode

My friend and I are collaborating on a small project involving a VR simulation that requires audio instructions. While everything functions smoothly in the web version and even on mobile devices, we encountered an issue when switching to VR mode on mobile ...

When attempting to access /test.html, Node.js server returns a "Cannot GET"

Embarking on the journey of diving into Pro AngularJS, I have reached a point where setting up the development environment is crucial. This involves creating an 'angularjs' directory and placing a 'test.html' file in it. Additionally, o ...

Dynamically load scripts in angularJs

Having multiple libraries and dependencies in my angularjs application is posing a challenge as I want to load them all using just one script, given that three apps are utilizing these dependencies. Currently, I have this custom script: var initDependenci ...

Exploring Typescript for Efficient Data Fetching

My main objective is to develop an application that can retrieve relevant data from a mySQL database, parse it properly, and display it on the page. To achieve this, I am leveraging Typescript and React. Here is a breakdown of the issue with the code: I h ...

Having trouble finding the element during Selenium JavaScript testing

I need help testing a JavaScript script using Selenium, but I am running into an issue. I cannot seem to find a specific element that I want to click on. Here is a snippet of my JS code where I am trying to click on the Shipping option. I have tried us ...

Identify the significance within an array and employ the filter function to conceal the selected elements

I'm in the process of filtering a list of results. To do this, I have set up a ul list to display the results and checkboxes for selecting filter options. Each item in the ul list has associated data attributes. When a checkbox with value="4711" is c ...

The data insertion query in MYSQL seems to be malfunctioning

I am facing an issue with inserting data from a form into a database table named "sumation". Despite using PhpStorm IDE, I am getting errors indicating that no data sources are configured to run the SQL and the SQL dialect is not set up. Can anyone help ...

Refresh the custom JavaScript dropdown list without having to reload the page

I implemented this code to customize a drop-down list Selector. Is there a way to reset this code without reloading the page, maybe by triggering a function with a button click? <button onclick="reset();">Reset</button> For example, if "Jagu ...

Material UI Input Field, Present Cursor Location

Is there a way to retrieve the current cursor (caret) position in a MaterialUI text field? https://material-ui.com/components/text-fields/ I am looking to make changes to the string content at a specific index, such as inserting a character X between cha ...

Tips for toggling the visibility of a <div> element using PHP code inside

I'm having trouble with a dropdown list that is supposed to show/hide some divs containing PHP files. However, when I try to toggle the visibility of the divs using the dropdown list, it doesn't seem to work as expected. Can anyone help me figure ...

Conceal Bootstrap Toast for a day following dismissal

I have implemented Bootstrap 5 toasts to showcase an advertisement on my website. The goal is to make the advertisement disappear for 24 hours once the user closes it. Here's the current code snippet: <div class="position-sticky bottom-0" ...

What is the method for obtaining the input value of an input type number in HTML?

Within my form, there is a number field where users can input scores: <input type="number" min="0" max="100" class="form-control" name="total_score" id='total_score' value="<?php echo $total_score;?>" >(Please input a score from 0-10 ...