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

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

我正在使用 Three.js,我想做一些重构。我想设置一个 class 专用于楼层生成的“楼层”:

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

在我的 main.js 中被调用为:

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

一切似乎都正常,但浏览器的控制台显示“未捕获的类型错误:无法设置未定义的 属性 'map'”:

我不知道如何摆脱这个错误。

#编辑:

答案是:

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

你声明了 floorMat 但没有初始化它,这是未定义的。你设置了它的地图,但它不是material的类型。你说它需要更新,但它刚刚被初始化。然后声明 material 并忽略 floorMat.