Refresh the texture mapping within ThreeJS

Hey there! Just wanted to share that I was able to find a solution by using

mesh.material.map.image.src = texture;

Here was the original question:

I'm working on a ThreeJS project and I'm trying to change the texture on a mesh. Unfortunately, I'm having trouble getting Three to update to the new texture.

I've already tried everything mentioned in similar questions on Stack Overflow, but nothing seems to be working so far:

  • three.js change texture on material
  • How to update texture in ThreeJS with loaded image data?
  • Three.js Update Texture image
  • Changing texture and color on Three.js collada object
  • and more...

The specific texture I'm trying to change is

scene.children[0].children[1].material.map.sourceFile
and the hierarchy looks like this:

  • SCENE scene
    • 3DOBJECT banner
      • MESH flag
        • MESHBASICMATERIAL flag_M
          • TEXTURE flag_MT

The texture I want to update is flag_MT. Here are the methods I've attempted:

  • flag_M.needsUpdate = true;
  • flag_MT.needsUpdate = true;
  • flag_MT = THREE.ImageUtils.loadTexture(texture);
    where texture is a base64 data string
  • basically recreating the entire object and replacing it in the scene

Thank you for any help.

Edit: Here are some key parts of the code:

init()

// Code snippet here

app.setFlagTexture()

// Another code snippet here

Answer №1

In a recent project, I encountered a similar issue where it seems that your initial attempt should have actually worked: flag_M.needsUpdate = true;

An alternative approach would be to recreate a texture using ImageUtils like so:

flag_MT = THREE.ImageUtils.loadTexture(texture);
, followed by setting flag_M.needsUpdate = true;. This method might suffice for occasional updates, but may not be ideal if textures are frequently changed. In such cases, manually updating the image source within the Texture Object and setting the needsUpdate flag to true could be more efficient.

For instance, in my implementation, the following steps were taken:

mesh.material.materials[0].map.image = { data: array, width: 20, height: 20 };
mesh.material.materials[0].map.needsUpdate = true;

Here, mesh refers to a cube with a FaceMaterial, and array represents an Uint8Array buffer containing RGB data. It is advisable to optimize performance by avoiding unnecessary deletion and creation processes purely for texture updates, as they can be resource-intensive for both the GPU and bus bandwidth.

If you continue to face issues, consider sharing your code for further assistance, as your initial approach should have achieved the desired outcome.

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

Moving Rows Between AgGrids

Experimenting with the example provided in this link (Dragging Multiple Records Between Grids) within my React application: https://www.ag-grid.com/react-data-grid/row-dragging-to-grid/ I have some inquiries; How can I retrieve the selected rows for the ...

jQuery's Offset().left is experiencing some issues and not functioning correctly

Do you have a question about the jQuery offset() function? On my website, I utilize it to show an "email a friend" window when the email icon is clicked. However, the problem is that the window ends up stuck to the right side of the browser's window ...

In React, the entire component refreshes every time the modal is opened

<ThemeProvider theme={theme}> <GlobalStyle /> {componentName !== 'questionaire' && componentName !== 'activityResult' && <CardWrapper />} <ErrorModal ...

In TypeScript, an interface property necessitates another property to be valid

In the scenario where foo is false, how can I designate keys: a, b, c, bar as having an undefined/null/optional type? Put simply, I require these properties to be classified as mandatory only when foo is true. interface ObjectType { foo: boolean; a: nu ...

What causes the disparity in functionality between simple html and css in an Angular 2 project compared to a vanilla html website?

When incorporating the following html/css into a new Angular project created with Angular CLI using 'ng new ProjectName', I encountered issues. Despite adding the CSS to app.component.css or styles.css and the HTML to app.component.html, the Angu ...

What steps can I take to stop Highcharts from showing decimal intervals between x-axis ticks?

When the chart is displayed, I want to have tick marks only at integer points on the x-axis and not in between. However, no matter what settings I try, I can't seem to get rid of the in-between tick marks. Chart: new Highcharts.chart('<some i ...

Recursive sorting and parsing of JSON data with multiple levels

I'm new to using recursion in JavaScript and need some guidance to understand it better. I have a JSON data structure with multiple levels of nested "subcategories". const STORE_CATEGORIES = [{ "Id":"1", "Name":"One Parent", ...

When executing the app.delete function, the req.body is found to be empty

I've encountered an issue when trying to send JSON data in an $http Delete call, as the req.body returned is coming back as an empty JavaScript object. Below is my $http delete call where "scenario" is a json object: //Deletes the item from the data ...

What is the best way to make a container 100% tall and display a navigation bar?

Struggling to properly render my React page This is what I have: ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router /> </Provider> </React.StrictMode>, document.getEl ...

What is the best way to flip the direction of the text input for a Calculator?

I am currently working on creating a basic calculator from scratch using HTML, CSS, and JavaScript. I have been trying to figure out how to align the numbers to the right side of the input element. Can anyone provide me with guidance on how to achieve thi ...

Easily Update Your Div Content by Simply Clicking a Single Link/Button

I am in need of assistance here. My goal is to display dynamic content within a div. Below you will find the code I currently have: <script type="text/javascript"><!-- function AlterContentInContainer(id, content) { var container = documen ...

Node application experiencing issues retrieving SVG files during production

When testing my application locally, the svg files display correctly with the code below (Angular.js variables are used within curly brackets): <img ng-src="img/servant_{{servant.personality}}.svg" draggable="false"> However, once deployed on Herok ...

The Beauty of Organized Data: Understanding Multiple Columns in VUE JS Projects

I'm currently developing a VUE JS app that calculates route costs for employees based on specific route details. I am looking to create a VUE JS component that will only display a dropdown list with three columns: List of countries Day fee for each ...

When an attempt to make a POST request using fetch() is made, a TypeError: Failed to fetch error is immediately thrown instead of

My front-end form is posting data using the fetch() function. Everything works fine and I get the correct response from the server when it runs smoothly without any interruptions. However, when I debug the server endpoint, it throws a TypeError: failed to ...

The notify.js fails to display notifications in the event of an error

Why am I not receiving any error notifications even when there is an error message in the response object? $.ajax(settings).done(function (response) { if ( "error_message" in response ) { console.log(response); $.notify(" ...

The URL in an AJAX request includes a repeating fragment due to a variable being passed within it

const templatePath = envVars.rootTemplateFolder + $(this).attr('link'); console.log("templatePath : ", templatePath); $.ajax({ method: "GET", url: templatePath, context: this, success : function(result){ ...

Patience is key while waiting for Meteor.loggingIn() to be false

I need help implementing authentication on a React route using Meteor and React.js. Here is my current approach: <Router history={browserHistory}> <Route path="/vendor/chat" component={VendorChat} onEnter={requireVendorAuth} /> </Route ...

Manipulate all vertex positions in a circular motion centered around a specific pivot point or axis using Three.js and GLSL

I'm exploring ways to manipulate the coordinates of objects in a Three.js environment around a specific central point or axis. Imagine placing a tube within the scene and seeing everything else in the scene curve around that axis while maintaining a c ...

When working with Angular1+ ES6 and using controller as a class, the utilization of Dependency Injections may be ambiguous within controller functions

I recently started using ES6 class for defining my controller, and here is the syntax I am using: export class SearchBarController { constructor($log) { 'ngInject'; $log.debug("Hello"); } textTyped($log){ $ ...

Toggle the visibility of dropdown list items in different ways: Add or Remove, or Show or

Currently, I am working on a project that involves 3 drop down lists for security questions. I have implemented javascript functionality that triggers an alert when a selection is made in any of the drop down boxes. My challenge now is figuring out how t ...