Encountering issues when dynamically altering the material texture in three.js during runtime

Having full control over a material, changing its color at runtime is seamless. However, attempting to change the map texture results in an error.

For instance:

var materials = mesh.material.materials;
materials[index].color.setHex(0xb60430);
materials[index].needsUpdate = true;
scene.render();

The aforementioned code works perfectly fine. But in a similar scenario:

var materials = mesh.material.materials;
var texture = new THREE.Texture(myPreloadedImageObject);
materials[index].map = texture;
materials[index].needsUpdate = true;
scene.render();

An error occurs (unable to copy from node-webkit console):

[.WebGLRenderingContext]GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 1

Note that removing the material like this also does not trigger any error:

materials[index] = 0;
scene.render();

s9k on the github issues section recommended:

geometry.buffersNeedUpdate = true;
geometry.uvsNeedUpdate = true;

Following this advice resolved the error, however, it did not change anything. When trying to set both color and material, no changes are applied even though the material appears to have the correct textures set upon inspection after rendering.

Any thoughts or suggestions? Could this be a bug?

Answer №1

Check out this cool demo using three.js r68 to change textures on a box geometry:

See it in action here:

Take a look at the code snippet below:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var geometry = new THREE.BoxGeometry(3,3,3);
var texture = THREE.ImageUtils.loadTexture( "a.png" );  
var texture2 = THREE.ImageUtils.loadTexture( "b.png" ); 
var material = new THREE.MeshBasicMaterial({color: 0x00ff00, map:texture});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;
var frame = 0;

function render() {
    frame++;
    if (frame > 120) {
        material.map = texture2;
        material.needsUpdate = true;
        console.log('texture change')
    }
    if (frame > 240) {
        material.map = texture;
        material.needsUpdate = true;
        frame = 0;
        console.log('texture change')
    }

    requestAnimationFrame(render);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
};

render();

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

Displaying JSON data in a div: a step-by-step guide

This HTML code is currently static. <div class="EquipmentContent row"> <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 subSection" style="float:right;background:#dff0ff;"> <section class="col-xs-12 col-sm-2 cl-md-2 col-lg-2 ...

Tips for configuring jQtree to initially display the tree structure from the HTML source

Up to this point, I have utilized jQuery TreeView for the navigation menus on my website. However, as the main navigation menu has grown significantly in size (40869 bytes out of 67054 bytes), I am seeking a way to streamline it by using AJAX calls to fetc ...

Unable to save captured signature image during saveEvent function in React Native

I am a beginner in the world of React Native and I am facing an issue with saving a signature image. It seems like the function responsible for this task is not being called properly. I suspect there might be an issue with the onPress event handler, as whe ...

What is the best way to determine the width and height of text within a TextArea using JavaScript in an HTML document

Imagine this scenario: https://i.stack.imgur.com/cliKE.png I am looking to determine the size of the red box within the textarea. Specifically, I want to measure the dimensions of the text itself, not the dimensions of the entire textarea. The HTML code ...

Is there a more efficient method to achieve the desired effect without making multiple calls to jQuery ajaxSuccess?

Currently, I am working on creating an effect that involves a quick fade-out followed by a fade-in of the element once the request is successful. Since jQuery processes elements in a routine manner (top to bottom), I have managed to achieve my desired eff ...

Tips for simulating an axios request that returns an image buffer

I am attempting to simulate an axios api call that returns an image buffer as shown below: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e1 00 de 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 06 00 12 01 03 00 01 00 00 00 01 00 ... ...

Encountering issues trying to display state value retrieved from an AJAX call within componentDidMount in React

I recently implemented an AJAX call in my React application using Axios, but I am a bit confused about how to handle the response data. Here is the code snippet that I used: componentDidMount() { axios.get('https://jsonplaceholder.typicode.com/us ...

What sets apart the Jquery Function Template from the Method Template?

Can someone explain the difference between Jquery Function Templates and Method Templates and how to properly utilize them? Below is a snippet of a Function Template and Method Template, but what sets them apart? Function Template:- (function($){ $.f ...

Determine the Placement of Bootstrap Popover by Utilizing SVG and Mouse Coordinates

Is there a way to dynamically reposition the popover that currently appears to the right of the Circle SVG? I would like to either base its position on the user's mouse click within the CircleSVG or move it to the exact center of the SVG, including bo ...

Is it possible to place an open div panel between two tweets?

I'm in the process of developing a UI with Twitter feeds. I want to create a feature where a panel can be opened between two tweets, causing the tweet below to shift downwards. This function is commonly seen in tweet clients like TweetBot; as each new ...

How can touchEvents in Three.js Mobile iOS v8.4 be handled as mouseEvents?

Based on data from caniuse.com, it appears that webgl is compatible with Safari and Chrome browsers on iOS versions 8.1 to 8.4. Testing from an iPad running the mobile version of iOS 8.4, it seems that many of the official Three.js webgl demos function pr ...

React Router relies on a DOM for Browser History to function properly

I am currently developing my app using React.js and express. My main focus right now is setting up react-router-dom for the application. Unfortunately, I encountered a warning when attempting to run the app: Invariant Violation: Browser history needs a ...

Creating a dropdown menu with data loaded dynamically using ajax and json, all without relying on jquery

I am looking to populate a few select menus using JSON data retrieved from my PHP script. Each select menu should display different values based on the selections made in the other menus. While I understand how to clear and fill a select menu using JavaScr ...

Improving the functionality of multiple range slider inputs in JavaScript codeLet me

Is it possible to have multiple range sliders on the same page? Currently, all inputs only affect the first output on the page. Check out an example here: http://codepen.io/andreruffert/pen/jEOOYN $(function() { var output = document.querySelectorAl ...

Creating dynamic visual elements on a webpage using HTML: Video

As I continue to learn HTML, CSS, and JavaScript to create a basic website for educational purposes, I have successfully embedded a video stored in my drive using the video element on an HTML page. However, I now aim to also display the video's title, ...

ng grid shift select issue mistakenly selects extra rows

Take a look at my plunker here: link var app = angular.module('app', []); // encountering a silly error that prevents me from pasting the entire code, please refer to the plunker for details To replicate the issue: Click on the first row with ...

Signal processing aborted as QML QObject was destroyed prematurely

While working in QML, I'm incorporating a C++ library that produces a QObject responsible for executing a process and triggering a signal upon completion. To handle this signal in JavaScript, I utilize the connect method of the emitted signal (success ...

Explaining the jQuery $.post method

After a thorough search, I finally discovered the importance of adding return false; at the end of my JQuery code for posting data. Without it, my code wasn't functioning as expected. As a beginner in JQuery, I would appreciate some insights into the ...

Trouble accessing JSON file on FileZilla/FTP server

When I transfer my project to the FTP server, the JSON file I am using for data is not functioning properly. However, when I run the program on XAMP, my local server, it works perfectly. Upon inspecting the element on the FTP server, I noticed that the JSO ...

Express JS encountering Firebase Google Sign-In glitch

Whenever a user clicks a button on the HTML page, this function is triggered. The function resides in auth.js and it is called from the server.js page. auth.js const firebase = require("firebase"); static googleSignIn(req,res){ firebase.aut ...