The update function for colors in Three.js is not being triggered when colorsNeed

I'm attempting to change the color of a face on an external event - button click. Despite searching for solutions, none have been successful so far. I have an interactive model that I want to be able to toggle its colors.

The model is rendered and colored during init(), where faces are iterated through and colored accordingly.

geometry = new THREE.Geometry().fromBufferGeometry( object );
var faceIndices = [ 'a', 'b', 'c' ];
for ( var i = 0; i < geometry.faces.length; i ++ ) {
    var face  = geometry.faces[ i ];
    for( var j = 0; j < 3; j++ ) {
        color = new THREE.Color( 0xff0000 );
        face.vertexColors[ j ] = color;
    }
}

Next, the material and its flags are set:

var material = new THREE.MeshPhongMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors} );
material.needsUpdate = true;
var solidModel = new THREE.Mesh( geometry, material );
solidModel.dynamic = true;
solidModel.name = "solid";

The model is then added to the scene for rendering:

scene.add( solidModel );

This process works fine. However, when I trigger the color() function on click, nothing happens:

console.log("Coloring...");
// Color the object
var solid = scene.getObjectByName("solid"); // retrieve the object from the scene
// change colors
for ( var i = 0; i < solid.geometry.faces.length; i ++ ) {
    var face  = solid.geometry.faces[ i ];
    for( var j = 0; j < 3; j++ ) {
        color = new THREE.Color(  0xffffff );
        color.setHex( Math.random() * 0xffffff );
        face.vertexColors[ j ] = color;
    }
}
// raise the update flag
solid.geometry.colorsNeedUpdate = true;

Even removing the solid object from the scene and adding a new one with the same geometry didn't work. It's interesting to note that in the chrome debugger, the colorsNeedUpdate flag on the "solid" object is indeed true at rendering time.

I'm using three.js r84.

Any insights would be appreciated.

Answer №1

Give this a shot:

for (let index = 0; index < shape.geometry.faces.length; index++) {
  let face = solid.geometry.faces[index];
  for (let j = 0; j < 3; j++) {
    face.vertexColors[j].setHex(Math.random() * 0xffffff);
  }
}

Check out the jsfiddle demonstration

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

Tips for storing Ajax request information into separate variables

Seeking a way to store data returned from an ajax call into separate variables. Ajax Call $.ajax({ url: 'fetch_lat_lng.php', type: 'GET', dataType: "html", success: function(data) { //executed on successful response ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

Obtaining a JavaScript proxy from a WCF service using webHttpBinding

I have configured all the necessary endpoints, bindings, and behaviors to consume a service using JSON. However, I am struggling to find a way to generate a JavaScript proxy for accessing the service from my client-side JavaScript with jQuery through Ajax. ...

Issue: $injector:unpr Angular Provider Not Recognized

I've recently developed an MVC project and encountered an issue regarding the loading of Menu Categories within the layout. <html data-ng-app="app"> . . . //menu section <li class="dropdown" ng-controller="menuCategoriesCtrl as vmCat"> ...

Struggling to pass express.js router requests and responses to a class method

I am struggling with setting up an Express JS router. I am facing difficulty passing req and res to my class method. Not Working app.get('/', controller.index) Working app.get('/', (res,req) => controller.index(req,res) The routi ...

Exploring the Functionality of ngMousedown and ngMouseup in AngularJS

Is it viable to apply ngMousedown to add a class to a div, and then use ngMouseup to remove the class once more? Currently, I am utilizing ng-mousedown="activateClass()". Within the activateClass() function, I modify $scope.className="data-active", which i ...

Traversing through an array and populating a dropdown menu in Angular

Alright, here's the scoop on my dataset: people = [ { name: "Bob", age: "27", occupation: "Painter" }, { name: "Barry", age: "35", occupation: "Shop Assistant" }, { name: "Marvin", a ...

Incorporating JSON information into highcharts for advanced data visualization

If I were to utilize JSON code from a specific website, such as this one: "", in order to incorporate it into my highcharts implementation. The data seems to consist of x_min, x_max, and price_data values. What would be the best approach for creating hig ...

PHP object representing a datetime in JSON format

How can I convert a JSON datetime object sent to JavaScript into a JavaScript datetime object? The PHP return is: "date": { "lastErrors": { "warning_count":0, "warnings":[], "error_count":0, "errors":[] }, "timezone": { "nam ...

Defining variables within a jQuery function

Within my initialization function (init), I have defined some variables and an animation that utilizes those variables. The challenge arises when I want to use the same animation/variables in my clickSlide function. http://jsfiddle.net/lollero/4WfZa/ (Un ...

Error message: "An unexpected character '<' was found at the beginning of the JSON data while loading a glTF file in a Three.js

Trying to incorporate a .glTF file into a Three.js project using the GLTFLoader in my Vue application has been presenting challenges. Each attempt at loading the .gltf file with the GLTFLoader results in the following error being displayed in the console: ...

Once you address a block using jQuery

$(function(){ $(window).scroll(function () { var scrollVal = $(this).scrollTop(); var adscrtop =$(".header").offset().top // 在 RWD 767以下不作動 if(window.screen.width>767){ if(sc ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

Optimize Vue code by utilizing constants from methods in computed properties

I don't have an issue, but I'm curious to find out if there is a way to streamline this code: ddd In the canDelete() function, I now require the isOwner parameter as well. I ended up duplicating the code from the canUserApprove() method, which ...

Having trouble with submitting the second stage of a multi-step form through Ajax technology

I'm currently tackling a multi-step form project using JavaScript, specifically focusing on submitting the second step of the form via Ajax. I've taken the initiative to create a distinct JavaScript file titled ajaxRequest.js to manage the Ajax r ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

Double firing of beforeUpdate event observed in Vue for recursive components

Recently delving into the world of vue js, I've been tinkering around with a recursive tree example inspired by the official example found here. While the original example starts with treedata containing a single root and multiple children, my goal w ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

How can I add a new property to an object type within an Interface in TypeScript?

I'm currently exploring how to merge declare an interface, with the twist of adding a property to the object literal type instead of directly to the interface itself. Within a library, I have a type that looks like this: interface DefaultSession { ...

"Exploring the usual progress of a standard GET request using Axios

My Objective: I am utilizing Vue And Axios, with the goal of displaying the progress in percentage on the console. The Challenge: The request itself takes around 4 seconds or more because it fetches a large amount of data, processes it into an excel fil ...