Tips for dynamically swapping out a texture image on a 3D model in three.js using Maya runtime

This website is currently loading a Maya model using the three.js library. The model includes various texture pictures.

Below is the JavaScript code:

 var SCREEN_WIDTH = window.innerWidth;
 var SCREEN_HEIGHT = window.innerHeight;

 var container;

 var camera, scene;
 var canvasRenderer, webglRenderer;

 var mesh, zmesh, geometry, materials;

 var windowHalfX = window.innerWidth / 2;
 var windowHalfY = window.innerHeight / 2;

 var meshes = [];

 function init() {

     container = document.createElement('div');
     document.body.appendChild(container);

     camera = new THREE.PerspectiveCamera(75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000);
     camera.position.x = 400;
     camera.position.y = 200;
     camera.position.z = 400;

     scene = new THREE.Scene();

     // LIGHTS
     var ambient = new THREE.AmbientLight(0x666666);
     scene.add(ambient);

     var directionalLight = new THREE.DirectionalLight(0xffeedd);
     directionalLight.position.set(0, 70, 100).normalize();
     scene.add(directionalLight);

     // RENDERER
     webglRenderer = new THREE.WebGLRenderer();
     webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
     webglRenderer.domElement.style.position = "relative";

     container.appendChild(webglRenderer.domElement);

     var loader = new THREE.JSONLoader(),
         callbackKey = function (geometry, materials) {
             createScene(geometry, materials, 0, 0, 0, 6)
         };
     loader.load("chameleon.js", callbackKey);

     window.addEventListener('resize', onWindowResize, false);

 }

 function createScene(geometry, materials, x, y, z, scale) {

     zmesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
     zmesh.position.set(x, y, z);
     zmesh.scale.set(scale, scale, scale);
     meshes.push(zmesh);
     scene.add(zmesh);
 }

 function onWindowResize() {

     windowHalfX = window.innerWidth / 2;
     windowHalfY = window.innerHeight / 2;

     camera.aspect = window.innerWidth / window.innerHeight;
     camera.updateProjectionMatrix();

     webglRenderer.setSize(window.innerWidth, window.innerHeight);
 }

 function animate() {
     for (var i = 0; i < meshes.length; i++) {
         meshes[i].rotation.y += .01;
     }
     requestAnimationFrame(animate);
     render();
 }

 function render() {
     camera.lookAt(scene.position);
     webglRenderer.render(scene, camera);
 }
 $(document).ready(function () {
     init();
     animate();
 });

Now I would like to change the first texture picture to a different one while keeping the rest of the textures the same at runtime. How can I achieve this?

Answer №1

To modify the texture during runtime, you can access the zmesh object's material and swap out the desired material for the blue dress. Although your model may have an array of materials, changing a single material object is simple - just update mesh.material.map . In this case, use

 mesh.material.materials[index].map 
. Add the following code to the end of your createScene function to replace the dress with an eyeball texture:

zmesh.material.materials[1].map = THREE.ImageUtils.loadTexture( 'c006_10.jpg' );

Remember to change 'c006_10.jpg' to the correct path for your eyeball texture. Additionally, if you want to trigger the texture swap using an onclick event, ensure that there is an active render loop or call the renderer's render function to display the changes.

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

Developing a void or vacancy using three.js

Thinking about creating a unique shape in three.js, similar to a 3x3x3 cube with a 1x1x1 hole in it. Is there a way to use cubegeometry initially and then apply another geometry to remove the unwanted parts, like a deletion geometry? :D Appreciate any hel ...

Learn how to retrieve a jqGrid ajax Nested Array of Json string in C# using Newtonsoft Json

I am attempting to parse a JSON string and extract the array values within it. {"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\ ...

Error message in Vuex4: Unable to access 'state' property because it is undefined

Having trouble with Vue3 and Vuex4, I keep encountering this error: Uncaught TypeError: Cannot read properties of undefined (reading 'state') at ReactiveEffect.eval [as fn] (App.vue?3dfd:36) at ReactiveEffect.run (reactivity.esm-bundler.j ...

When a JSON stringified string contains a space-separated value, it can cause the data attribute to break

let dataObject = { "Cast_Code": "NA", "Mat_Code": "xxxx", "Pin_Num": "xxxx", "MatDetail": [ { "Batch_Number": "Patch PA", "Batch_Expiry": "No Expiry", "Batch_Quantity": "xxx", "Return_ ...

Change a 24-hour time variable to 12-hour time using AngularJS/jQuery technology

I have a value retrieved from the database in a 24-hour time string format. I am seeking a solution to convert this string into a 12-hour clock time using either AngularJS or jQuery. Currently, I am unable to make any changes to the back-end (JAVA) or the ...

How can I determine the appropriate time to hide the loading screen after the model has been loaded with gltfLoader and before the scene is rendered?

I am currently working on a project using threejs version 106, where I have integrated both the webGLRenderer and CSS2DRenderer. My main challenge lies in loading a glb model and displaying a loading progress bar utilizing the onProgress callback of the l ...

javascript Href and onclick malfunctioning

I am encountering an issue with a form on my webpage: <form name="myForm" id="myForm" method="post" action="someUrl.php"> ... </form> There is a div outside of this form which contains an anchor link: <a href="anotherUrl.php" onclick="doc ...

Unleashing the Power of Node Js: Retrieving File Data and Form Data in POST Requests

When sending form data values using Postman, you can utilize a NodeJS server in the backend to handle the POST request. Here is an example of how to structure your code: require('dotenv').config(); const express = require('express'); co ...

Utilizing AJAX and jQuery to dynamically load a div instantly, followed by automatic refreshing at set intervals

I am utilizing jQuery and AJAX to refresh a few divs every X seconds. I am interested in finding out how to load these divs immediately upon the page loading for the first time, and then waiting (for example, 30 seconds) before each subsequent refresh. I h ...

Manipulating images live with options for scaling, resizing, and cropping

I am currently developing a content management system that allows users to upload images and attach them to different sections of the pages. My goal is to find a user-friendly, preferably jQuery-based plugin for resizing images before they are cropped. A ...

axios replicates the URL within the interceptor

I am currently using Axios for my HTTP requests, and I have encountered an issue for the first time. The initial request goes through smoothly, but on the second request, Axios is inexplicably duplicating my URL. The URL that Axios is attempting to fetch ...

Display a random div element in jQuery without specifying a specific class

I have a dynamic list that I am displaying in a div as shown below <div class="cards card1"> <div class="front"> <p>Front 1</p> </div> <div class="back1" style="display: none"> <p>Back 1</p> ...

Is there a way to extract the data from a UIWebView?

Is there a way to extract the first paragraph of each page from a UIWebView? I'm currently struggling with this task. I've tried using a regular expression for detection, but unfortunately it's returning the paragraph class name instead of ...

Using DIV to "enclose" all the elements inside

I need assistance with my HTML code. Here is what I have: <div id="cover" on-tap="_overlayTapped" class$="{{status}}"> <form method="POST" action="/some/action"> <input required id="name" name="name" label="Your name"></input> ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

How to Process a Stripe Payment using jQuery AJAX (JavaScript Only)

I'm in the process of creating a custom payment form for Stripe and I want to manually initiate the AJAX call to connect with Stripe. Instead of relying on a typical submit event. Unfortunately, it seems like I might be sending the request to the inc ...

Is there a way to implement jQuery on dynamically added content?

I created a page that closely resembles a Facebook wall, with posts, comments for each post, and a "send" button to add new comments. In this example: The posts are identified by the class "mypost". The "send-comment" button is located within a div with ...

`How can I activate caching for getServerSideProps in Next.js?`

We have implemented server-side rendering for a few pages and components. In an attempt to optimize performance, we have been experimenting with caching API responses. export async function getServerSideProps(context) { const res = await getRequest(API ...

Utilizing jQuery and AJAX for submitting multiple POST requests

Experiencing a problem with posting data via AJAX using a drag and drop interface. The data is being sent to the POST URL as intended, but there's a recurring issue where the POST request occurs twice, causing the processing URL to handle the data aga ...

Determine whether the values in the array are arranged in ascending or descending order

I'm currently working on a code problem where I need to loop over the values of an array and determine whether they are in ascending order, descending order, or neither. The function I've written so far is not giving me the correct results, but I ...