首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >三个js - Textures加载- async / await

三个js - Textures加载- async / await
EN

Stack Overflow用户
提问于 2021-08-02 21:38:54
回答 1查看 297关注 0票数 1

我上了一堂绘画课:

代码语言:javascript
复制
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;
    }
}

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

代码语言:javascript
复制
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();
}

无论如何,

代码语言:javascript
复制
    console.log(allTextures[0]) 

在loadingWorld返回中:

图像仍然是未定义的。我很确定这个问题来自于:

代码语言:javascript
复制
textureLoader.load(pathName)

我乐于接受任何建议!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-02 22:24:19

load method接受回调。它不会返回任何可以调用resolve的东西。不要使用所有这些promiseTextureBack代码,只需使用返回promise的loadAsync method

代码语言:javascript
复制
const allTexturesPromises = drawingPaths.map(pathName => {  
    return textureLoader.load(pathName);
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68628199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档