Search code examples
javascriptthree.jscallbacktexturesloader

Three.js - TextureLoader - load - callback - Uncaught TypeError: Cannot set property 'map' of undefined


I'm using Three.js and I wanted to do some refactoring. I want to set a class "Floor" dedicated to the floor generation:

    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;
        }
    }

which is invoked in my main.js as:

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

Everything seems to work fine but the browser's console displays "Uncaught TypeError: Cannot set property 'map' of undefined":

enter image description here

I can't figure out how to get rid of this error.

#EDIT:

The answer was:

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;
    }

Solution

  • you declare floorMat and do not initiate it, which is undefined. You set its map, but it's not a type of material. You say it needsUpdate, but it's just been initialized. You then declare material and ignore floorMat.