Coloring vertices in a Three.js geometry: A guide to assigning vibrant hues

This inquiry was previously addressed in this thread: Threejs: assign different colors to each vertex in a geometry. However, since that discussion is dated, the solutions provided may not be applicable to current versions of three.js. The latest versions no longer support the attribute vertexColors for the Geometry class.

I am aware that it's feasible to designate the color of each face of a geometry. In my case, I am assigning the vertices of a sphere varying distances and aim to adjust the color of each vertex based on its distance from the center simultaneously.

Answer №1

It seems like this solution might help with what you're looking for (even though I'm not too familiar with Three.js):

The important thing, as mentioned by user morris4, is to set the colors on the face rather than the geometry itself.

Make sure to also specify the 'vertexColors' property in the material so that it displays correctly.

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

geometry = new THREE.CubeGeometry( 10, 10, 10 );

for ( var faceIndex in geometry.faces )
{
    var face = geometry.faces[ faceIndex ];
    face.vertexColors[ 0 ] = new THREE.Color(0xFF0000);
    face.vertexColors[ 1 ] = new THREE.Color(0x00FF00);
    face.vertexColors[ 2 ] = new THREE.Color(0x0000FF);
    face.vertexColors[ 3 ] = new THREE.Color(0xFFFFFF);
}

var material = new THREE.MeshBasicMaterial({ color: 0xFFFFFF, vertexColors: THREE.VertexColors });

var object = new THREE.Mesh( geometry, material );

object.position.z = -25;

scene.add(object);

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

I've uploaded this code snippet to a fiddle at: http://jsfiddle.net/87mcD/3/

Keep in mind that this was tested on r54 and may not work exactly the same on newer versions like r63.

However, it could still be useful for your project...

EDIT: Here's an updated fiddle for three.js r.63: http://jsfiddle.net/87mcD/4/

Answer №2

Upon conducting a quick grep search (attempt grep "vertexColors" */*.js . in the src directory of three.js), it seems that in recent versions of three.js, you can only set the color per face, rather than per vertex. Each triangle face may have a vertexColors property containing 3 colors aligned to the vertices of the face.

To assign colors to each vertex, you will need to determine which faces use that particular vertex and then set the colors on the faces' vertexColors property.

Update: Depending on your specific needs, you could iterate over the faces, retrieve the 3 vertices using the face's indices (a, b, c), and calculate and assign the color to them. This method may compute the same color multiple times (potentially around 8 times per vertex in your case), but it provides a simple and efficient way to achieve your objective.

function color(v) {
    var c = new THREE.Color();
    c.r = (10 + v.y)/20;
    c.g = (10 + v.y)/10 + Math.sin(v.x/10 * Math.PI) - 0.3;
    c.b = 1 - (10 + v.y)/20;
    return c;
}

for(var i = 0; i < geometry.faces.length; ++i) {
    var face = geometry.faces[i];
    face.vertexColors[0] = color(geometry.vertices[face.a]);
    face.vertexColors[1] = color(geometry.vertices[face.b]);
    face.vertexColors[2] = color(geometry.vertices[face.c]);
}

Fiddle: http://jsfiddle.net/87mcD/5/

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

Looking for a jQuery Gantt Chart that includes a Treeview, Zoom functionality, and editing capabilities?

I am in need of integrating a dynamic Gantt Chart tool into a room booking solution using jQuery. The Gantt chart should be highly interactive, allowing for drag-and-drop functionality, a tree view on the left to group tasks, and a zoom feature for adjusti ...

What does the reportProgress function do in HTTP services with JavaScript?

Can someone explain the functionality of reportProgress in JavaScript, specifically when used with Angular Typescript? I am having trouble finding documentation on this. return this.httpClient.request<ProductResponse>('get',`${this.basePath ...

Has Apache initiated a forced logout process?

Running a LAMP server, I have implemented Apache basic authentication to log in users accessing the server homepage. I am currently seeking a way to enforce user logout, but my attempts with mod_session & mod_auth_form have not been successful. The page ...

Cross-Domain Image Uploading

I've been attempting to enable image uploads from one domain to another (CORS). Everything runs smoothly on Localhost, but when I try it on an actual domain, I consistently encounter this message in the Developer Console: Invalid request In my uplo ...

Show only specific items in an AngularJS application

As a newcomer to AngularJS and the Ionic framework, I'm currently working with the basic Starter Tabs Ionic template. I would like to implement a "Favourite/Bookmark" feature for certain items and display them on a separate tab. The structure of my b ...

Implement a jQuery DataTable using JSON data retrieved from a Python script

I am attempting to create an HTML table from JSON data that I have generated after retrieving information from a server. The data appears to be correctly formatted, but I am encountering an error with DataTable that says 'CIK' is an unknown para ...

In MUI v5 React, the scroll bar vanishes from view when the drawer is open

Currently, I am working on developing a responsive drawer in React using mui v5. In the set-up, the minimum width of the drawer is defined as 600px when it expands to full width. However, an issue arises when the screen exceeds 600px - at this point, the d ...

Gather numerical values and transform them into dates using AngularJS

My Angularjs project involves 3 scopes for year, month, and day which are retrieved from 3 input boxes. I need to combine them into a date, but the current code inserts the date with an additional 22:00:00 like 2019-06-01 22:00:00.000. How can I insert the ...

Utilizing slid.bs.carousel to retrieve values upon slide change

I am working on incorporating Bootstrap 4's Carousel with jQuery and PHP to create an odometer that dynamically changes its value on each slide. My plan is to utilize .addClass based on the length of the value. One challenge I am facing is that when ...

Highlight particular terms (key phrases) within text contained in a <td> tag

I am currently working on a project and facing a challenge that I am unfamiliar with. My task is to highlight specific keywords within text located inside a <td> element. I cannot manually highlight the keywords as the texts are dynamic, originating ...

Enhancing a React Native application with Context Provider

I've been following a tutorial on handling authentication in a React Native app using React's Context. The tutorial includes a simple guide and provides full working source code. The tutorial uses stateful components for views and handles routin ...

How can I fetch a value from a database and set it as the selected option in a

I am facing an issue with the usage of the selectpicker plugin from Bootstrap in order to select multiple items. My requirement is to create a modal for editing where the data is fetched from previous records, particularly an array. I am looking for a way ...

JavaScript does not display checkbox values

I am currently testing whether checkbox values appear on the client side. When I execute the code, the alert is not showing anything. I would greatly appreciate any assistance, thank you. <div> <label name="finishing"class=" ...

Removing White Spaces in a String Using JavaScript Manually

I have created my own algorithm to achieve the same outcome as this function: var string= string.split(' ').join(''); For example, if I input the String: Hello how are you, it should become Hellohowareyou My approach avoids using ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

How can I show a title when redirecting a URL in VUE JS?

My current setup includes a navigation drawer component that changes the title based on the user's route. For example, when navigating to the home page (e.g. "/"), the title updates to "Home", and when navigating to the profile page (e.g. /profile), t ...

What does the underscore before a function in JavaScript or PHP signify?

I am curious about the significance of the underscore symbol (_) when it is placed before a function or variable. Does it serve to simply describe something, or is it required for executing specific functions or calling certain methods? In JavaScript: va ...

Having trouble with res.redirect not working after the page has been rendered with data?

I have a basic forget password feature set up, where users can request a password change and receive an email with a token. Clicking the link in the email will redirect them to a page where they can input their new password. When I click on the email link ...

Troubleshooting: Next.js - Issues with encodeURIComponent function when using `/` in getStaticPaths

Reproducible site showcasing the issue: Reproducible code example: https://github.com/saadq/nextjs-encoding-issue Homepage Food page The goal is to dynamically create static pages for different food items based on their titles. This functionality works ...

updating the row of an html table with elements from a javascript object

I am faced with the task of dynamically adding rows to a table based on the number of elements in my JavaScript object. The object consists of keys and arrays of values. userobject={ ID: [1,2,3] IP_Address: ["12.21.12 ...