Is it possible to dynamically change the color of a face in Three.js PlaneGeometry based on the value of its vertices?

Is there a way to dynamically change the color of a face without pre-creating a materials palette and then assigning based on vertex value? Here is my current code:

var materials = [];
materials.push([..] //add all the materials here.

var geometry = new THREE.PlaneGeometry(gs, gs, size, size);
$.getJSON('http://localhost:5000', function (data) {
    for (var i = 0, l = geometry.vertices.length; i < l; i++) {
        geometry.vertices[i].z = data.map[i] / 255;
        if (geometry.vertices[i].z > 1) {
            geometry.faces[i].materialIndex = 1;
        } else {
            geometry.faces[i].materialIndex = 0;
        }
    }
    var plane = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
    scene.add(plane);
});

I would like something along the lines of:

[..]
    $.getJSON('http://localhost:5000', function (data) {
        for (var i = 0, l = geometry.vertices.length; i < l; i++) {
            geometry.vertices[i].z = data.map[i] / 255;
            if (geometry.vertices[i].z > 1) {
                geometry.faces[i].setrgb(i*128, i*2, i*96);
            } else {
                geometry.faces[i].setrgb(i*12, i*2, i*96);
            }
        }
[..]

Thank you!

Answer №1

As an illustration

var size = 10; // used as a simple example
...
planeGeom = new THREE.PlaneGeometry(size, size, 10, 10);
...
planeGeom.faces.forEach(function(face){
  var val = planeGeom.vertices[face.a].y;
  face.color.setRGB(Math.abs(val) / size * 2, 0, 0);
});
planeGeom.colorsNeedUpdate = true;

When assigning colors with r, g, b components, keep in mind that the values must range from 0 to 1, not 0 to 255. Each face corresponds to a Face3 object, containing properties a, b, c where vertex indices are stored.

Check out this jsfiddle for reference

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

Incorporate data into the div element

I've been attempting to populate a div after selecting 3 different options from select boxes, but nothing seems to be happening. I have confirmed that the PHP function works as expected when tested manually, but I'm unable to get it to populate a ...

"Is there a way to eliminate an object from $scope without having to loop through the

I have a jsfiddle that you can check out here. In the fiddle, we are able to add new nodes and delete all children in the parent node. However, my question is how can I delete a specific child without having to iterate through the array? I am aware that w ...

Trouble with loop functionality in AJAX append feature

My Ajax call is shown below: $.ajax({ type: "POST", url: '@Url.Action("SubMenuOrderingGetId", "Admin")', data: JSON.stringify({ selectManuId: selectManuId }), dataType: "text", contentType: "application/json; charset=utf-8", ...

The passport has an expired or incorrect code entered

I'm encountering an issue where the code passed is showing as incorrect or expired. The specific error message reads: "TokenError: The code passed is incorrect or expired." GET /api/users/auth/github/callback?code=afefcf8b12561c910798 - - ms - - [ ...

Creating a Javascript function to mirror an HTML object

Essentially, I have HTML code that includes variables html = `<div>${product.id}<img src="${product.src}"/></div>` then I simply update the DOM with: document.querySelector('.container').innerHTML = html; Everything seems to ...

Rotation Ensuring a Seamless Transition to a Specific Angle

I'm currently trying to figure out how to rotate an object at a speed of 160 degrees per second, gradually slowing down until it comes to a stop at a specific angle. For instance, if the target angle is set to 30 degrees, the object should spin quickl ...

Generating data within an express route (with the use of socket.io-client)

Recently, I made the decision to refactor my code in order to separate the front and back end, which were previously combined into one service. However, I am now facing an issue where I need the web server to emit data to the data server after validation. ...

Exploring the scope of event listeners in jQuery's TimeCircles

Currently experimenting with the jquery timer known as "TimeCircles", which can be found here. I have successfully set up a minute / second timer for 30 minutes with an alert that triggers at 25 minutes. My goal is to implement an event when the timer hits ...

Supply context to node package

I've encountered an issue with the code below, where sometimes the content is not passed correctly: var app = require('buildersApps'); app.addContent({ folderPath: __dirname + '/content/' }); app.start(); To address thi ...

How do I retrieve the NodesValue from the childNodes in an HTML tag?

<p title="The test paragraph">This example demonstrates some <b>HTML content that may be<br>present</b> in your file</p> txt=document.getElementsByTagName("p")[0].childNodes[0].nodeValue; alert("<p>The text from the in ...

Updating the content of a list item on the fly using React

After spending all day on this, I am feeling a bit frazzled. Trying to achieve what would take 20 seconds in JQuery has proven to be quite the challenge in React ¯\_(ツ)_/¯ In my application, tags are ranked by importance from 1 to 9. Simple enoug ...

Disabling the button using props will prevent its onClick event from triggering

For a quick solution, visit the react code sandbox and test the buttons by clicking them a few times. The Buggy button fails to reach the end of the slideshow. I am developing a horizontally scrollable slideshow. https://i.sstatic.net/51viM.gif The slid ...

Change the color of the status bar icon in cordova to create the opposite effect

Looking to modify the color of the icons and fonts on my status bar. Similar to the design on Soundcloud... I was able to change the background to white, but now the icons blend in because they are also white Example of Soundcloud's status bar Statu ...

What is the best way to transfer information from a server running Express.js to a client using React.js?

When using Express.js, I have the ability to send an HTML file that includes a React component. app.get('/index', function(req, res) { res.sendFile(path.join(__dirname + '/src/index.html')); }); Suppose I want to send a uniqu ...

Is there a way to simulate the parameters injected into an fs callback without actually interacting with the filesystem during testing?

I'm currently utilizing Chai, Mocha, and Sinon for my testing framework. At the moment, I have a functioning test, but I find myself having to set up a directory and populate it with files just to make my tests run successfully. This approach doesn&a ...

Is it possible for Vue to retrieve refs on mounted during nextTick following the dynamic import of the component?

Utilizing Nuxt js and Element UI, I have dynamically imported Element UI plugins in the plugins folder. export default () => { Vue.component("ElForm", () => import("element-ui/lib/form")); Vue.component("ElFormItem", ...

Converting Geometry into BufferGeometry

From my understanding, Geometry contains a javascript object structure of the vertices and faces, while BufferGeometry stores raw WebGL data using Float32Arrays, etc. Is there a method to convert regular Geometry into BufferGeometry, which is more memory ...

Dynamic jQuery backstretch feature: automatic image cycling and reversing

I am currently using backstretch on my website and attempting to create a continuous loop of the moving image by automatically shifting it from left to right and back. However, I am facing difficulties as the background only moves in one direction. I am se ...

The React Functional Component undergoes exponential re-renders when there is a change in the array

I'm encountering a problem with one of my functional components. Essentially, it maintains an array of messages in the state; when a new message is received from the server, the state should update by adding that new message to the array. The issue ar ...

Having issues with InstaFeed (search) feature and jQuery Mobile

As a new developer, I am working on my first JQM site. However, I am facing an issue with my search input form where the instafeed photos do not show up until after a manual page refresh following submission. Despite numerous attempts, I cannot seem to res ...