【问题标题】:Three js - Textures Loading - async / await三个 js - 纹理加载 - 异步 / 等待
【发布时间】:2021-10-08 04:43:43
【问题描述】:

我做了一个绘图课:

export class Drawing {
    constructor(texture) {        
        const material = new MeshBasicMaterial({
            color: 0xffffff,
            map: texture
        });
        this.mesh = new Mesh(new PlaneGeometry(texture.image.naturalWidth / 20, texture.image.naturalHeight / 20), material);
    }

    setPosition(x, y, z) {
        this.mesh.position.x = x;
        this.mesh.position.y = y;
        this.mesh.position.z = z;
    }
}

我想访问 texture.image 属性以设置 PlaneGeometry。因此,在调用绘图对象之前,我会执行一些异步/等待调用来加载纹理(绘图调用是在 World 构造函数中进行的):


let world;
let raycasterDown;
let prevTime = performance.now();
const direction = new Vector3();
const globalInputs = new GlobalInputs();
const textureLoader = new TextureLoader();

const promiseTextureBack = (pathName) => {
    return new Promise((resolve) => {
        resolve(textureLoader.load(pathName));
    });
}

const allTexturesPromises = [];
drawingPaths.map(pathName => {          //drawingPaths is an array of string
    allTexturesPromises.push(promiseTextureBack(pathName));
});

const loadingWorld = async () => {
    const allTextures = await Promise.all(allTexturesPromises); 
    console.log(allTextures[0]);
    world = new World(allTextures);
    document.body.appendChild(world.renderer.domElement);
    world.instructions.addEventListener('click', function () {
        world.controls.lock();
    });
    world.controls.addEventListener('lock', function () {
        world.instructions.style.display = 'none';
        world.blocker.style.display = 'none';
    });

    world.controls.addEventListener('unlock', function () {
        world.blocker.style.display = 'block';
        world.instructions.style.display = '';
    });
}

init();

function init() {
    loadingWorld();
    raycasterDown = new Raycaster(new Vector3(), new Vector3(0, -1, 0), 0, 10);
    document.addEventListener('keydown', (event) => {
        globalInputs.onKeyDown(event);
    });

    document.addEventListener('keyup', (event) => {
        globalInputs.onKeyUp(event);
    });
    window.addEventListener('resize', onWindowResize);
    animate();
}

尽管如此,

    console.log(allTextures[0]) 

在 loadingWorld 中返回:

而且图像仍然未定义...我很确定问题来自:

textureLoader.load(pathName)

我愿意接受任何建议!

【问题讨论】:

    标签: javascript async-await three.js loader image-size


    【解决方案1】:

    load method 接受回调。它不会返回您可以调用 resolve 的任何内容。而不是所有这些promiseTextureBack 代码,只需使用返回承诺的loadAsync method:

    const allTexturesPromises = drawingPaths.map(pathName => {  
        return textureLoader.load(pathName);
    });
    

    【讨论】:

    • 你成就了我的一天!谢谢!
    猜你喜欢
    • 2022-01-25
    • 2017-09-11
    • 1970-01-01
    • 2015-08-31
    • 2013-11-12
    • 2018-04-04
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    相关资源
    最近更新 更多