Updating a Texture Image in Three.js

I'm currently working on a minecraft texture editor using three.js, with a similar interface to this. My goal is to implement basic click-and-paint functionality, but I'm facing challenges in achieving this. I have textures for each face of every cube, and I apply them through shader materials using the functions below.

this.createBodyShaderTexture = function(part, update)
{
    sides = ['left', 'right', 'top', 'bottom', 'front', 'back'];
    images = [];
    for (i = 0; i < sides.length; i++)
    {
        images[i] = 'img/'+part+'/'+sides[i]+'.png'; 
    }
    texCube = new THREE.ImageUtils.loadTextureCube(images);
    texCube.magFilter = THREE.NearestFilter;
    texCube.minFilter = THREE.LinearMipMapLinearFilter;
    if (update)
    {
        texCube.needsUpdate = true;
        console.log(texCube);
    }
    return texCube;
}
this.createBodyShaderMaterial = function(part, update)
{

    shader = THREE.ShaderLib['cube'];
    shader.uniforms['tCube'].value = this.createBodyShaderTexture(part, update);
    shader.fragmentShader = document.getElementById("fshader").innerHTML;
    shader.vertexShader = document.getElementById("vshader").innerHTML;

    material = new THREE.ShaderMaterial({fragmentShader: shader.fragmentShader,  vertexShader: shader.vertexShader, uniforms: shader.uniforms});
    return material;
}

SkinApp.prototype.onClick = 
function(event)
{
    event.preventDefault();
        this.change(); //testing: changes texture file to a red square
    this.avatar.remove(this.HEAD);

    this.HEAD = new THREE.Mesh(new THREE.CubeGeometry(8, 8, 8), this.createBodyShaderMaterial('head', false));
    this.HEAD.position.y = 10;
    this.avatar.add(this.HEAD);
    this.HEAD.material.needsUpdate = true;
        this.HEAD.dynamic = true;
}


When the user clicks anywhere on the mesh, the texture file is updated using canvas. Although the update is successful, the changes are not immediately visible in the browser and require a page refresh. I've researched ways to change the texture image to a new file, but I'm unsure if it's possible to show changes within the same texture file during runtime. If this isn't feasible, I'd appreciate suggestions for alternative approaches.

Answer №1

When updating a texture, whether it's from a canvas, video, or external source, it's essential to set a specific property on the texture to ensure it refreshes correctly:

For instance, if you create an object like so:

let canvas = document.createElement("canvas");
let canvasTexture = new THREE.Texture(canvas);
let material = new THREE.MeshPhongMaterial();
material.map = canvasTexture;
let mesh = new THREE.Mesh(geometry, material);

After making changes to the texture, make sure to set the following property to true:

mesh.material.map.needsUpdate = true;

Upon rendering the scene again, the updated texture will be displayed properly.

Answer №2

If you're looking to learn more about updating objects in three.js, check out this comprehensive guide:

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

What are the steps to gather user data and generate a roster of individuals currently online?

I am currently working on a way to gather information about the users who are currently logged into my website. Here's how it works: When a user enters my website, they have the option to choose a nickname using an input box. Then, there are five diff ...

"Learn how to securely redirect to a custom URI scheme with a fail-safe option to display alternative content if not supported

In short: Can a visitor be redirected to a custom URI scheme or shown alternate content if the scheme is not supported? My specific scenario involves developing a mobile app that utilizes a custom URI scheme for users to invite others to actions within th ...

What is the best way to access a variable from one JavaScript file in a different file?

Currently, I have a simple cube scene set up in Three.js Now, my goal is to add camera movement using perlin noise. To achieve this, I found and incorporated the Perlin noise library into my project: https://github.com/josephg/noisejs I then included th ...

The operation to assign a value to property 'two' cannot be completed as it is currently undefined

I'm facing an issue with the code below and cannot figure out why I am encountering the error message. I have ensured that each object contains a value, so why is there a reference to 'undefined'? Cannot set property 'two' of unde ...

The JQuery CSS function is unable to alter the height of the element

I am working with a grid that contains various elements, each with the class item. When I click on one of these elements, I toggle the class expand to resize the element. <body> <div class="grid"> <a href="#"> < ...

Can a file be imported into Node.js without the need for packaging?

Is there a way to have an entire file evaluated in node? For example, let's say I want to evaluate the angular.js source file. An example of what the code could look like is as follows: jsdom = require("jsdom").jsdom; document = jsdom("<html>& ...

Leveraging "setState" in React Native with Promises

I am facing a challenge in updating the state of a React Component with data obtained from an API call. I encountered an issue where using the setState function within the promise resulted in an error "Type Error: _this2.setState is not a function" in Reac ...

My React application came to an unexpected halt with an error message stating: "TypeError: Cannot read properties of undefined (reading 'prototype')"

Everything was running smoothly with my app until I encountered this error without making any significant changes: TypeError: Cannot read properties of undefined (reading 'prototype') (anonymous function) .../client/node_modules/express/lib/resp ...

Performing a reverse image search request using Javascript/AJAX to query Google

I have been attempting to perform a reverse image search request using AJAX, but I keep receiving 302 errors. After checking the Firebug console, I discovered that the response header from Google contains a URL linking me to the results. However, I am unsu ...

Navigating through Routing Express and sending data to a template

If I have the following code in my router.get() function, how can I output a template with the data without being able to use res.render()? router.get('/read', function(request, response) { res.send({"result": "Success sent from routes/index ...

Encountering the Firebase issue with error code (auth/invalid-api-key)

I keep encountering the error message 'Firebase: Error (auth/invalid-api-key) ' despite having entered all the correct authentication details. ...

`A brief disruption in loading the visual style of Google Maps`

Using the Ionic Framework, AngularJS, and Google Maps API, I encountered an irritating issue with my mobile app. Every time the map loads, there is a noticeable delay in loading the map style. This delay is particularly problematic as my map style converts ...

Concealing alert messages automatically in CodeIgniter PHP after a certain amount of time

After attempting to use a script to hide the flash message once displayed, I found that it was not working as expected. The flash message remains visible until the page is refreshed. Controller: if ($this->email->send()) { $this- ...

Extract all objects from an array where a specific field contains an array

data:[ { id:1, tags:['TagA','TagB','TagC'] }, { id:2, tags:['TagB','TagD'] }, { id:3, tags:[&a ...

How can I display the value of a radio button that has been chosen?

Would you mind sharing how to display the selected value of a radio button? I attempted it this way, but unfortunately, it did not work. You can view my code at this link. <mat-radio-group [(ngModel)]="favoriteName"> <mat-radio-button *ngFor="l ...

Combining Server-Side HTML with React Components and Functions: A Guide

Utilizing Vue makes it simple for me to incorporate a Vue application as a container above the server-side rendering HTML like so: <body> <div id="appMain"> <!-- This serves as the primary element for Vue --> <!-- ...

What is the reason that the attr function fails to function in this particular scenario?

I want to implement a functionality where clicking on an input field clears its value, but I can't seem to make it work. Here is the HTML code: <input id='input' type="text" name="phppostvar" value="clear this"></input> This i ...

Differences in jQuery selector behavior when targeting elements in parent windows compared to popup windows

In order for my userscript to function correctly, I have implemented a temporary solution. To create code that is easier to understand and maintain, it's essential for me to gain a deeper understanding of WHY the temporary fix works. Here is some code ...

Improving Performance in AngularJS Through Efficient Scope Passing Between Controllers

I am facing a situation in my AngularJS project where I have two controllers - controller 1 is constantly present in the view, while controller 2's visibility can change based on the view. In order to ensure that controller 1 has access to certain sco ...

Tips for effectively interpreting a json string

Trying to extract specific fields from a JSON string and display them on an HTML page, but encountering the following error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data This is the JSON being sent: { "Order0& ...