I am interested in dynamically changing the texture/material of a .obj file during runtime with the click of a button using three.js

Whenever I try to load my model and change its texture, the model doesn't load and nothing appears on the screen. I am new to three.js/webgl languages and javascript. Can someone please provide me with the correct information to move forward? Below is the code snippet: https://drive.google.com/open?id=0BxJJ7XpRqKz4S3JONlAwSHJxdFk, this link contains the assets used in this project.

// Once everything is loaded, we run our Three.js content.
function init() {

    var stats = initStats();

    // Create a scene to contain objects, cameras, and lights.
    var scene = new THREE.Scene();

    // Define a camera 
    var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);

    // Set up renderer and define size
    var webGLRenderer = new THREE.WebGLRenderer();
    webGLRenderer.setClearColor(new THREE.Color(0xaaaaff, 1.0));
    webGLRenderer.setSize(window.innerWidth, window.innerHeight);
    webGLRenderer.shadowMapEnabled = true;

    // Position and point the camera towards the scene center
    camera.position.x = 100;
    camera.position.y = 40;
    camera.position.z = 50;
    camera.lookAt(scene.position);
    scene.add(camera);

    // Add spotlight for shadows
    var spotLight = new THREE.DirectionalLight(0xfa93e5);
    spotLight.position.set(30, 40, 50);
    spotLight.intensity = 0.5;
    scene.add(spotLight);

    // Append the renderer's output to the HTML element
    document.getElementById("WebGL-output").appendChild(webGLRenderer.domElement);

    // Render function
    var step = 0;


    // Setup control gui
    var controls = new function () {
        // We need the first child since it's a multimaterial


    };

    var gui = new dat.GUI();

    // Load model
var loader = new THREE.OBJLoader();
loader.load( 'sofa 1.obj', function (object) );






var sofa = new THREE.Mesh(object,fabric_1);
    var texture = new THREE.ImageUtils.loadTexture("defaultMat_Base_Color(1).png");
    var texture2 = new THREE.ImageUtils.loadTexture("defaultMat_Base_Color_1.png");

    var material = THREE.ImageUtils.loadTexture("defaultMat_Normal_DirectX bump.png");
    var material1 = THREE.ImageUtils.loadTexture("sofa new final4 high-AO_u0_v0.png");
    var material2 = THREE.ImageUtils.loadTexture("lambert2SG_Roughness specular.png");

    var fabric_1 = new THREE.MeshPhongMaterial(
    { fabric_1.map = texture;
      fabric_1.normalMap = material;
      fabric_1.aoMap = material1;
      fabric_1.specularMap = material2;  });


    var fabric_2 = new THREE.MeshPhongMaterial(
    { fabric_2.map = texture_2;
      fabric_2.normalMap = material;
      fabric_2.aoMap = material1;
      fabric_2.specularMap = material2;

    });

    scene.add(sofa),

    function setfabric_1 () {
        sofa.traverse(function(child){
        if(child instanceof THREE.Mesh){
          child.material = fabric_1;
          }
          sofa.geometry.uvsNeedUpdate = true;
          sofa.needsupdate = true;
        });
        } 

    function setfabric_2 () {
        sofa.traverse(function(child){
        if(child instanceof THREE.Mesh){
          child.material = fabric_2;
          }
          sofa.geometry.uvsNeedUpdate = true;
          sofa.needsupdate = true;
        });
        } 

    render();


    function render() {
        stats.update();

        if (mesh) {
            mesh.rotation.y += 0.006;
            ;           
        }

        // Render using requestAnimationFrame
        requestAnimationFrame(render);
        webGLRenderer.render(scene, camera);
    }

    function initStats() {

        var stats = new Stats();
        stats.setMode(0); // 0: fps, 1: ms

        // Align top-left
        stats.domElement.style.position = 'absolute';
        stats.domElement.style.left = '0px';
        stats.domElement.style.top = '0px';

        document.getElementById("Stats-output").appendChild(stats.domElement);

        return stats;
    }
}
window.onload = init;

Answer №1

Utilize uniforms in order to connect local variables with the shader, remember to load the textures beforehand. For more information, visit threejs.org/uniforms. Another option is to use

"uTexArray" : { type: "tv", value: [ new THREE.Texture(), new THREE.Texture() ] } // texture array (regular)

click here for details

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

Harnessing the power of source material through a veil of shadows

How can I apply a material to create a stained glass effect in shadows? https://i.sstatic.net/uNMKu.jpg (source: 123rf.com) While I can currently project shadows, they appear as plain grey and do not match the source object's material. ...

Using Angular's ng-repeat directive to iterate over a list of <li> elements containing strings with

Query: <li ng-repeat='msg in msgs'>{{msg}}</li> Directive: msgs=['abc','a b v', '123'] msgs.push('Something entered from textarea, possibly containing line breaks') ...

steps for setting up an endless scroll masonry grid

I have incorporated masonry js to display content on my website. Now, I am interested in adding infinite scrolling functionality using this script. I came across a demo that showcases this feature. However, I am struggling to figure out how to implement ...

Dragging a div element within a table

I am working on an HTML code where I need to make the colored divs draggable and fit them into specific table cells. The green div should occupy 2 cell spaces, light blue 3 cell spaces, yellow 4 cell spaces, and dark blue 5 cell spaces. While I have the d ...

My Vue frontend project is encountering an error during compilation that states "this relative module module was not found."

I have created a vue frontend to interact with my spring backend, which is working well. However, when I compile the frontend, it compiles to 98% and shows an error message: ERROR Failed to compile with 1 error 11:24:51 The relative module was not foun ...

Instead of using a hardcoded value, opt for event.target.name when updating the state in a nested array

When working with a dynamically added nested array in my state, I encounter the challenge of not knowing the key/name of the array. This lack of knowledge makes it difficult to add, update, iterate, or remove items within the array. The problem lies in fun ...

Unexpected syntax error encountered when shutting down the route, unable to recover

const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.get('/split/name', (req, res) => ...

When attempting to loop through an Observable that is of type array using *ngFor, the error message "Cannot read property 'subscribe' of undefined

I can't figure out why this isn't working, even though it seems straightforward. I'm using a service that gives me an observable. There are a few rxjs streams connected to it in the following way: search(searchTerm: string { this.search ...

Saving Pictures in Database Without Using jQuery

Hey there fellow developers, I'm currently immersed in a web project that involves reconstructing a social media platform similar to snapchat. To capture images, I am utilizing my webcam with JavaScript and saving the image data to a variable named i ...

Looking to switch up the hide/show toggle animation?

Currently, I have a functioning element with the following code. It involves an object named #obj1 that remains hidden upon page load but becomes visible when #obj2 is clicked. #obj1{ position:fixed; width:100px; bottom:180px; right:10 ...

The mystery of the missing body in a Node.js post request

I have developed an API in Node.js and I am facing an issue with the POST method where the body is coming as undefined. How can I extract the value passed using fetch? Node.js Code------------------------------------------ const express=require('expr ...

Guide to retrieving a string value rather than Json output with a mongodb aggregate function

I have a function that retrieves the value of the 'minHospitalization' field from the database. The response from this function is '[{"minHospitalization":1}]' Instead of returning the value in JSON format, I want to return just ' ...

Is it possible to execute an ajax function at regular intervals until a specific condition is fulfilled?

My application consists of two JSP pages. One is responsible for the UI, while the other processes the response. UICounter.jsp: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Page</titl ...

The API response was blocked due to the CORS header "Access-control-allow-origin."

I have an index.html file that is used for making HTML and Ajax calls. When I run the file through localhost, the API works perfectly. However, if I directly open the index.html file in Google Chrome or Mozilla Firefox, I encounter a CORS (Cross-Origin Re ...

There was an error in parsing JSON data because the input value is missing a property name or '}'

One challenge I am facing is converting the value from a hidden input field into a JSON object when a button is clicked. The HTML code for the hidden input field looks like: <input type="hidden" name="product-data" value="{Product: 'Premium', ...

Reading a JSON file using Javascript

I've been trying to work with the Coingecko API, but I'm having trouble parsing the data. The sample data can be found here: This is the code snippet I've been using: $.getJSON( "https://api.coingecko.com/api/v3/exchanges", function( dat ...

Retrieve information from an external source and subsequently make alterations to it

If a certain external site returns a string like "cost is 10$", is it possible for me to display it as "price:10$" on my own website using only Javascript? The external site could be something like Facebook.com. My website, of course, belongs to me. Hello ...

What methods can be used to ensure a required minimum delay time between function executions?

For my node function, I am aiming for a specific execution delay of around 5 seconds. The minimum delay needs to be implemented within the function itself, not externally, so external users are unaware of the delay. Therefore, I cannot rely on modules l ...

How can I alter the color of a face on a mesh that I imported into Three.js?

I'm having trouble figuring out how to change the color of a mesh imported from Blender in three.js. Any guidance on this issue would be greatly appreciated. Furthermore, I'm interested in learning how to make a specific face (or any face from a ...

Is there a more efficient method for replacing all attributes on cloned elements?

While this code does the job, I can't help but feel like it's a bit outdated. I'm not very experienced with JS/JQuery and only use them when necessary. My approach involves cloning an element and then replacing all of its attributes with on ...