Issues occur in React when attempting to load an image using TextureLoader in three.js

I have encountered some difficulties while trying to incorporate three.js into a React project. Despite my efforts, I am unable to successfully load texture images. I have set up my own local server, included a callback method for when loading is finished, and attempted to load the images from various paths, but nothing seems to be working.

The images are located in

public/animation/js/img/texture1.png
, and the animation file is in public/animation/js/animation.js. Here is the current code I am working with:

const Pilot = function () {
  let faceMaterial;
  const geometry = new THREE.CircleGeometry(10, 128);
  const manager = new THREE.LoadingManager();

  manager.onStart = function (url, itemsLoaded, itemsTotal) {
    console.log('Commenced loading file: ', url, '.\nLoaded ', itemsLoaded, ' of ', itemsTotal, ' files.');
  };
  manager.onLoad = () => {
    console.log('Loading finished!');
  };

  manager.onProgress = function (url, itemsLoaded, itemsTotal) {
    console.log('Loading file: ', url, '.\nLoaded ', itemsLoaded, ' of ', itemsTotal, ' files.');
  };

  manager.onError = function (url) {
    console.error('An error occurred while loading ', url);
  };

  const textureLoader = new THREE.TextureLoader(manager);

  textureLoader.setCrossOrigin('anonymous');

  textureLoader.load('/img/texture1.png',
    texture => {
      faceMaterial = new THREE.MeshFaceMaterial([
        new THREE.MeshBasicMaterial({ map: texture }),
        new THREE.MeshBasicMaterial({ map: texture }),
        new THREE.MeshBasicMaterial({ map: texture }),
        new THREE.MeshBasicMaterial({ map: texture }),
        new THREE.MeshBasicMaterial({ map: texture }),
        new THREE.MeshBasicMaterial({ map: texture })
      ]);
    },
    undefined,
    err => {
      console.error('An error occurred:', err);
    }
  );

  this.mesh = new THREE.Mesh(geometry, faceMaterial);
  this.mesh.name = 'profile';
};

Answer â„–1

Your image path may be causing the issue, especially if it is an absolute path like '/img/texture1.png'

To resolve this, consider the directory from which your web server is running. For example, if it is running from the /public directory, you will need to update the image path passed to the textureLoader's load method like this:

textureLoader.load('/animation/js/img/texture1.png',

Make sure that your mesh is using the same material instance that your texture data is loaded into. You can adjust your code as follows:

// Declare material instance outside of texture load handler
const faceMaterial = new THREE.MeshFaceMaterial([
        new THREE.MeshBasicMaterial(),
        new THREE.MeshBasicMaterial(),
        new THREE.MeshBasicMaterial(),
        new THREE.MeshBasicMaterial(),
        new THREE.MeshBasicMaterial(),
        new THREE.MeshBasicMaterial()
      ])

  const textureLoader = new THREE.TextureLoader(manager);

  textureLoader.setCrossOrigin('anonymous');

  textureLoader.load('/animation/js/img/texture1.png',
    texture => {
      // Apply the loaded texture to each sub material of the faceMaterial instance
      faceMaterial.materials[0].map = texture;
      faceMaterial.materials[1].map = texture;
      faceMaterial.materials[2].map = texture;
      faceMaterial.materials[3].map = texture;
      faceMaterial.materials[4].map = texture;
      faceMaterial.materials[5].map = texture;
    },
    undefined,
    err => {
      console.error('An error occured:', err);
    }
  );

  // Assign the faceMaterial instance to your mesh
  this.mesh = new THREE.Mesh(geometry, faceMaterial);
  this.mesh.name = 'profile';

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

Is it feasible to embed Instagram in an iframe without using the API?

Is there an alternative method to embed Instagram using iframe without the need for an API? ...

Why is it that this particular line of code sometimes gives me an "undefined" result before returning an actual value?

Why does the method 'equal' always return with an "undefined" followed by a number? And when I try to parse it, it returns me a NaN. <!DOCTYPE> <html> <head> <script> var fnum = 0; var secondNum; var operation; functi ...

Javascript: Dynamically Altering Images and Text

One feature on my website is a translation script. However, I'm struggling to activate it and update the image and text based on the selected language. This is the code snippet I am currently using: <div class="btn-group"> <button type ...

Step-by-step guide to showing the contents of every file in a directory on the console using node.js or express

Having trouble retrieving file contents from a folder using Node.js I can successfully retrieve the contents of one file using the read function, but unable to retrieve contents of all files at once. ...

Node.js and Express: tackling the problem of duplicate variables

I have a checkUser middleware that saves the user information when a JWT is verified. However, when I integrate it into my routes and attempt to log res.locals.user.username, the username appears twice in the console. This duplication is causing issues wit ...

What is the best way to differentiate and analyze new AJAX output from previous data using div elements?

Embarking on a project to develop a high/low game using JavaScript, I encountered a perplexing issue where the displayed numbers seemed to be out of sync with the variables stored. This discrepancy left me scratching my head as I struggled to get them to a ...

"Tips for stopping users from using Ctrl+U to view page source in

Is there a way to prevent users from viewing the source code (HTML + JavaScript) of a page by disabling Ctrl+U in the browser? ...

Retrieve JSON-formatted HTML content to display as HTML within a React component

Wondering how to make the link actually render as a clickable hyperlink. Currently, when I read this line of text from my Json file, React displays the link as plain text rather than a clickable link. someData.json [{ "about": "John has a blog you ...

Refreshing issue: Model change in child page not updating view correctly (Ionic & Angular)

I am currently working with Ionic 3.20 and Angular 5.2.9, encountering an issue with content refreshing after a model change. Despite being new to this, I sense that I might be overlooking something fundamental. Within my view, I have the following elemen ...

Extracting the URL of the @font-face declaration in CSS with the use of JavaScript

Currently, my CSS file contains numerous @font-face tags. Each tag specifies a unique font-family and src URL. @font-face{ font-family: Garamond; src: url('ePrintFonts/pcl_91545.ttf'); } @font-face{ font-family: C ...

Regarding a listener within a quiz game's event system

I'm dealing with an issue in my quiz-game. I'm curious if I need to implement an event-listener for refreshing the initial page with a question and 4 options. Can anyone guide me on how to do this? My questions are stored using JSON. Here is the ...

Sending JavaScript objects from React.js to Node.js

I send the object to the backend (Node js) when making an API call, but I am logging the objects for verification. Initially, I used POSTMAN to check and it worked perfectly. However, when attempting to pass an object in the frontend (Reactjs), it appear ...

Discovering the method to access a local function within a static function in Javascript ES6 (ES2015) or Typescript

Is there a way to access the non-static "foo2" method from inside the static "bar" method? So far, I'm only able to access the "foo1" and "foo3" methods. Can anyone provide guidance on how to achieve this? let foo1 = () => { alert('foo1†...

How can you create an animation that plays forward on the first click and then reverses on the second

After coming across numerous similar questions, I realize that most of them refer to the outdated .toggle() function. My main challenge lies in achieving the desired effect where div#p moves right on the first click and then returns to its original positio ...

Clicking on an element triggers the addition of a class, and the newly

Once the page has finished loading, I am able to utilize jQuery to add a specific class in the following way. $(document).ready(function() { $("#parent").click(function(){ $(".child").addClass("active"); }); }) ...

Guide to retrieving and editing images from Appwrite using Vue

Currently, I am utilizing a View frontend to retrieve a PDF file from Appwrite Storage. My goal is to acquire the PDF, insert additional text onto it, and then save it to the user's local device. Below is the code I have so far - although I can recei ...

Modifying the onclick function for a bootstrap glyphicon

How can I swap the .glyphicon-menu-down to glyphicon-menu-up when a user clicks on a link? Currently, it's not working as expected. Could there be an issue with my jQuery implementation? Markup <a data-toggle="collapse" data-parent="#accordion" h ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

Connecting Ionic/Angular directives to scrollbars

I'm having an issue with my scrolling div: <div class="list"> <div class="item" ng-repeat="post in posts"> <img src="post.img" is-visible/> </div> </div> and I've implemented this directive: angular.elemen ...

Adjusting height in Google Maps to fill the remaining space

Currently, I am developing a map application where I want the Google Maps DIV to occupy the remaining height under the header. Here is the code snippet: <!DOCTYPE html> <head> <title>Map Application</title> <style type ...