Trouble arises when attempting to add an image to a spherical object

I've searched through various threads, Googled extensively, watched YouTube tutorials.... But I can't seem to figure out how to apply a texture to my Sphere. When I run this code, all I see is a white Sphere without any texture showing up. Can someone please assist this newbie <3

Here's the complete code:

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() {
    return (
      <GraphicsView
        onContextCreate={this.onContextCreate}
        onRender={this.onRender}
      />
    );
  }

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

Answer №1

It's essential for Expo to fetch its resources from a local source rather than remote URLs.

To start, download the wall.jpg file and save it locally (I stored mine in a folder within the root directory named 'assets')

Next, you'll need to configure expo to include jpg files in your bundle. Access app.json in your app's root directory and make sure to update or add the "packagerOpts" section to include jpg:

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

You might also have to create a file called "metro.config.js" in your app's root directory with the following content:

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

Now that your packager is bundling JPG files into your expo app, you can utilize ExpoTHREE's loadAsync function to load your 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});

After applying these modifications, your code should be operational on my end. This process can be used to incorporate various file types into your bundle and load them using ExpoTHREE. Just remember to list the different filetypes in the arrays within your app.json and metro.config.js for them to be bundled and accessible in your app.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I use an input array to filter data in mongodb?

When receiving input from the front-end, it looks like this: { "options":[ { "optionId":"5ebbe0f56b197f36fc472168" }, { "optionId":"5ebbe1aa6b197f36fc47216e" } ] } The goal is to filter the data in a way that ...

I am unsure about implementing the life cycle in Svelte.js

Unknown Territory I am not well-versed in front-end development. Desire to Achieve I aim to utilize the lifecycle method with SvelteJS. Error Alert An error has occurred and the lifecycle method is inaccessible: ERROR in ./node_modules/svelte/index.m ...

Issues with validating the Google Maps API JavaScript tag

Currently working on updating a website to be fully validated with HTML5 using W3C standards. Having trouble validating the Google Maps API JavaScript tag in the code snippet below: <script src="http://maps.googleapis.com/maps/api/js?libraries=places& ...

Automatically activate a button when it comes into view while scrolling

I am currently working in Joomla, which makes it challenging to create a fiddle, but here is the concept: My website displays a mosaic grid of 12 articles upon loading, along with a 'Load More' button. When this button is clicked, an additional ...

The documentation for the 4-11.4 version of Material UI cannot be found anywhere

After the release of MUI v5.0.0-rc.1, it appears that all documentation pages for version 4, except for v4.12.3, have vanished. https://mui.com/versions/ Furthermore, (currently not accessible) Is there a way to access previous versions' document ...

The post body is incomplete and is lacking the necessary parameter "To" that

It seems there might be a configuration issue either in the header or the body. Should I make changes to the headers or is it possible that the body is misconfigured? const axios = require('axios'); const url = '/my_url'; const aut ...

What is preventing me from renaming a file in PHP when passed through jQuery?

Hello to all users! I've encountered an issue where I can't seem to change the file name in PHP that is being passed from jQuery: Here is the JavaScript code where I pass the file to the PHP handler: var url = '/temp.php'; var xhr = ...

Having difficulty retrieving a dropdown value with reactjs

Seeking assistance with retrieving dropdown values in ReactJS. Despite attempting multiple methods, I have been unsuccessful in obtaining the values. Can someone provide guidance on extracting these values? Below is a snippet of my code: <Grid container ...

Discovering the vacant fields within a database by looping through them

My goal is to download a .pdf document from the external database Contentful by utilizing an HTML link on a user interface. The issue arises when certain fields inside Contentful do not always necessitate a pdf document. In these cases, the field remains ...

JavaScript encountered an issue: Uncaught ReferenceError - 'userNumber' is undefined at line 43

I'm currently working on a JavaScript guessing game where I've already set up the necessary functions. However, I keep encountering an error. An error in my JavaScript code is causing a ReferenceError: userNumber is not defined on line 43 to b ...

Organizing various elements into separate divs with just one ajax request

I recently encountered an issue with my project involving an ajax call that was functioning correctly. $.get( 'accNoRealMovs1.jsp', {mode:"0"}, function(responseText){ $('#divAccMovementNR').html(responseTe ...

Ensure that all divs have the same height and padding when resizing

I have 3 divs nested within a parent div. My goal is to dynamically set the height of all the child divs to match the height of the div with the maximum height, even when the screen resizes due to responsiveness. Below is my HTML structure: <div class ...

Building a 3D Earth model using three.js for WebGL applications

I found a code online, but it doesn't seem to work. Can someone provide me with the HTML code needed to make it run in my browser? The original code was sourced from this website (github repository) Github code repository https://github.com/turban/ ...

Trouble With Ajax Submission in CakePhp: Issue with Form Serialization

In my attempt to utilize ajax for sending an array of objects along with serialized form data, I encountered a problem. The issue arises when I include the array in the ajax data along with the serialized form data. This results in the serialized form data ...

What causes Three.js OBJ conversion to render as mesh successfully but log as undefined?

I'm just getting started with Three.js and I'm experimenting a lot. Although I'm new to Javascript as well, the issue I'm facing seems to be more about variable scoping and callback function protocols than it is about Three.js itself... ...

Unveiling the Secrets of Unearthing Data from JSON

My code receives JSON strings through a JSONP call. Although I'm aware of the general JSON structure, I don't know the specific keys and values it will contain. The typical structure is as follows: [ {"key_name": "value"}, {"key_name": ...

What is the correct way to promise-ify a request?

The enchanting power of Bluebird promises meets the chaotic nature of request, a function masquerading as an object with methods. In this straightforward scenario, I find myself with a request instance equipped with cookies via a cookie jar (bypassing req ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...

What is the best way to change a string containing single quotes to double quotes in order to JSON parse it

My PHP code involves encoding an array using json_encode. $params = array(1=>'something','2'=>'two'); While the encoding process itself works fine, I encountered an issue when trying to embed the JSON data into an anc ...

Automatically populate input fields with text based on the option chosen from a dropdown menu

Having some issues here... I want to automatically populate the text input boxes in my form when a username is selected from the dropdown. The user data array is retrieved from a MySQL database. Not sure if my JavaScript code is correct. Here's my arr ...