在Sphere上应用图片时出现问题

时间:2019-04-02 19:46:51

标签: javascript three.js textures expo

我已经在这里阅读了很多主题,谷歌搜索了YouTube。...只是无法使我的Sphere获得纹理。运行此代码仅显示白色球形,但没有纹理...请帮助新手<3

下面的完整代码:

import { View as GraphicsView } from 'expo-graphics';
import ExpoTHREE, { THREE } from 'expo-three';
import React from 'react';

export default class App extends React.Component {
  componentWillMount() {
    THREE.suppressExpoWarnings();
  }

  render() {
    // Create an `ExpoGraphics.View` covering the whole screen, tell it to call our
    // `onContextCreate` function once it's initialized.
    return (
      <GraphicsView
        onContextCreate={this.onContextCreate}
        onRender={this.onRender}
      />
    );
  }

  // This is called by the `ExpoGraphics.View` once it's initialized

  onContextCreate = async ({
    gl,
    canvas,
    width,
    height,
    scale: pixelRatio,
  }) => {
    this.renderer = new ExpoTHREE.Renderer({ gl, pixelRatio, width, height });
    this.renderer.setClearColor(0x00cbff)
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(120, width / height, 0.1, 1000);
    this.camera.position.z = 5;
    const loader = new THREE.TextureLoader();
    const geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
    const material = new THREE.MeshPhongMaterial({map: loader.load('https://threejsfundamentals.org/threejs/resources/images/wall.jpg')});

    this.cube = new THREE.Mesh(geometry, material);
    this.scene.add(this.cube);

    this.scene.add(new THREE.AmbientLight(0x000000));

    const light = new THREE.DirectionalLight(0xffffff, 0.5);
    light.position.set(3, 3, 3);
    this.scene.add(light);
  };

  onRender = delta => {
    this.cube.rotation.x += 3.5 * delta;
    this.cube.rotation.y += 2 * delta;
    this.renderer.render(this.scene, this.camera);
  };
}

1 个答案:

答案 0 :(得分:0)

不确定这是否是一个绝对要求,但我相信expo需要从本地商店而不是远程URL加载资源。

首先,下载wall.jpg文件并将其存储在本地(在我的情况下,是位于根目录中名为“ assets”的文件夹。

现在,您需要配置expo以将jpg文件添加到包中。在应用程序的根目录中打开app.json并更新或添加到“ packagerOpts”,以便包含jpg:

    "packagerOpts": {
      "assetExts": ["jpg"]
    },

您可能还需要在应用的根目录中创建一个名为“ metro.config.js”的文件,该文件包含以下内容:

module.exports = {
  resolver: {
    assetExts: ["jpg"]
  }
}

现在,打包程序在expo应用程序捆绑包中包括JPG文件,您可以使用ExpoTHREE内置的loadAsync函数来加载jpg:

const texture = await ExpoTHREE.loadAsync(
  require('./assets/wall.jpg')
);
const geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
const material = new THREE.MeshPhongMaterial({map: texture});

通过这些更改,您的代码似乎可以正常工作了。您可以使用相同的过程将不同类型的文件添加到捆绑文件中,并加载它们以供在ExpoTHREE中使用。只需将各种文件类型添加到app.json和metro.config.js中的数组中,它们就会捆绑在一起供您在应用程序中使用。