Using Three.js to give distinct colors to individual vertices within a geometric shape

I am looking to implement picking functionality using IdMapping in Three.js

Due to concerns about performance, I have a single large geometry that is calculated as follows:

for (var i = 0; i < numberOfVertices; i += 9) {
  p1  = new THREE.Vector3(graphData.triangles.vertices[i+0], graphData.triangles.vertices[i+1], graphData.triangles.vertices[i+2]);
  p2  = new THREE.Vector3(graphData.triangles.vertices[i+3], graphData.triangles.vertices[i+4], graphData.triangles.vertices[i+5]);
  p3  = new THREE.Vector3(graphData.triangles.vertices[i+6], graphData.triangles.vertices[i+7], graphData.triangles.vertices[i+8]);
  geometry.vertices.push(new THREE.Vertex( p1.clone() ));
  geometry.vertices.push(new THREE.Vertex( p2.clone() ));
  geometry.vertices.push(new THREE.Vertex( p3.clone() ));
  geometry.faces.push( new THREE.Face3( i/3, i/3+1, i/3+2 ) );

geometry.colors.push(new THREE.Color(0xFF0000));
  geometry.colors.push(new THREE.Color(0xFF0000));
  geometry.colors.push(new THREE.Color(0xFF0000)); 
}

geometry.computeFaceNormals();
var material = new THREE.MeshBasicMaterial({});

var triangles = new THREE.Mesh( geometry, material );
scene.add(triangles);

Is there a way for me to assign unique colors to each vertex within my geometry?

Answer №1

Make sure to use geometry.vertexColors instead of geometry.colors (assign a color to each vertex).

Also, remember to update the material:

material = new THREE.MeshBasicMaterial({ vertexColors: THREE.VertexColors });

Answer №2

Currently, I am utilizing version 71 of the software. The solution provided by Lee may still be effective, but it appears overly intricate.

Below is a straightforward demonstration of creating a Mesh with individual color assignments for each vertex:

var geometry = new THREE.Geometry();

// Creating a basic shape - a triangle.
geometry.vertices.push(
    new THREE.Vector3(-10,  10, 0),
    new THREE.Vector3(-10, -10, 0),
    new THREE.Vector3( 10, -10, 0)
);

// Storing the face in a variable before adding it to the geometry.
var face = new THREE.Face3(0, 1, 2);

// Assigning colors to the vertices of the face.
face.vertexColors[0] = new THREE.Color(0xff0000); // red
face.vertexColors[1] = new THREE.Color(0x00ff00); // green
face.vertexColors[2] = new THREE.Color(0x0000ff); // blue

// Adding the face to the geometry.
geometry.faces.push(face);

// Using a specific material is crucial.
var material = new THREE.MeshBasicMaterial({vertexColors: THREE.VertexColors});

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

Hopefully, this explanation is less intimidating.

It's a drawback that colors are assigned to the face's vertices rather than directly to the geometry's vertices. This means repeating the color assignment process. Personally, I prefer having an interface built on top of Three.js to enable color assignments directly to geometry.

Answer №3

Utilize this snippet of code to generate a vivid RGB color cube in three.js version 49.

(Associated with How to alter face color in Three.js)

// Implementation of material for assigning colors to vertices
var vertexColorMaterial = new THREE.MeshBasicMaterial( { vertexColors: THREE.VertexColors } );

var color, point, face, numberOfSides, vertexIndex;

// Faces are labeled using characters
var faceIndices = [ 'a', 'b', 'c', 'd' ];

var size = 100;
var cubeGeometry = new THREE.CubeGeometry( size, size, size );

// Color allocation to vertices as intended
for ( var i = 0; i < cubeGeometry.vertices.length; i++ ) 
{
    point = cubeGeometry.vertices[ i ];
    color = new THREE.Color( 0xffffff );
    color.setRGB( 0.5 + point.x / size, 0.5 + point.y / size, 0.5 + point.z / size );
    cubeGeometry.colors[i] = color; // Utilizing this array for ease
}

// Transmission of colors to respective positions in each face's vertexColors array.
for ( var i = 0; i < cubeGeometry.faces.length; i++ ) 
{
    face = cubeGeometry.faces[ i ];
    numberOfSides = ( face instanceof THREE.Face3 ) ? 3 : 4;
    for( var j = 0; j < numberOfSides; j++ ) 
    {
        vertexIndex = face[ faceIndices[ j ] ];
        face.vertexColors[ j ] = cubeGeometry.colors[ vertexIndex ];
    }
}

cube = new THREE.Mesh( cubeGeometry, vertexColorMaterial );

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

Dynamically shift the table footer to the bottom of a scrolling div by utilizing jQuery

I'm facing a challenge where I need to relocate each th tag from the footer row of a table to the bottom of a scrolling div. You can check out the scenario on this link. Currently, I am able to achieve this by hardcoding it like so: $('.sticky- ...

Is it possible to rewrite this function recursively for a more polished outcome?

The function match assigns a true or false value to an attribute (collapsed) based on the value of a string: function match(children) { var data = $scope.treeData for (var i = 0; i < data.length; i++) { var s = data[i] for (var ...

show information retrieved from database according to the drop-down menu selection

Can anyone assist me with this query? I have a drop-down menu that includes "Shop A" and "Shop B". Shop A has a value of 1, and Shop B has a value of 2. When I select Shop A from the dropdown, I want to display the data from the database as a table specifi ...

Experiencing an infinite loop due to excessive re-renders in

I'm receiving an error and unsure of the reason. My goal is to create a button that changes colors on hover. If you have a solution or alternative approach, please share! import React, {useState} from 'react' function Login() { const ...

Waiting for multiple asynchronous calls in Node.js is a common challenge that many developers

I'm facing a dilemma trying to execute multiple MongoDB queries before rendering a Jade template. I am struggling to find a way to ensure that all the Mongo Queries are completed before proceeding with rendering the template. exports.init = funct ...

Just diving into JavaScript, what makes jQuery so powerful?

As a newcomer to javascript (although functional programming is no problem for me), I find myself questioning some of the design choices made by jQuery. Is it too late to make changes now, or are they simply too ingrained in the framework? For example, the ...

What is the best way to include the 'selected' attribute within the <li> element using jQuery or Javascript?

I am trying to dynamically add a 'selected' attribute by comparing the text within <li></li> elements <ul class="list"> <li data-value="0" class="option" selected>All Categories</li> < ...

JavaScript date formatting without using jQuery

Looking for help to apply a date mask (dd/mm/yyyy) on an ASP.net textbox. I have tried several JavaScript solutions found through Google search, but none seem to work seamlessly, especially with backspacing. Any suggestions for a reliable script would be ...

The resolution of deferred actions is not as successful as foreseen

In my code, I have a method that queries documentdb for a specific document and returns the results to the caller. fetch: function(query) { var fetchDeferred = q.defer(); client.queryDocuments(collectionLink, query).toArray(function(err, docs) { ...

Ways in which elements can be toggled through jquery or javascript?

There are various words listed below: word1 word2 word3 ... Every word in the list is linked to 1 to 3 examples. When a user clicks on a word, certain actions should take place. I want the examples to display when the associated word (e.g., word1) is c ...

Exploring the Various Textures within the CANVAS 2D Context

Exploring new techniques for filling the canvas, I am currently trying to add texture to an object similar to the blobs from the blob example (http://www.blobsallad.se/). The challenge is that the current example is utilizing the 2D context without webGL i ...

Transform a list of H1..6 into a hierarchical structure

I have a task to convert H1 to H6 tags from a markdown file into a JavaScript hierarchy for use in a Table of Contents. The current list is generated by AstroJS and follows this format [{depth: 1, text: 'I am a H1'}, {depth: 2: 'I am a H2}] ...

Bing Translator and XMLHttpRequest are two powerful tools for translating and

When running the code snippet below, I encounter an issue where I am not receiving status 200 and responseText. However, when using the following URL: http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appId=F1B50AB0743B541AA8C070890 ...

Failed installation of Semantic-ui through npm encountered

Encountering an error while attempting to install semantic-ui through npm for a new project. Here are the version details: $ node -v v16.14.0 $ npm -v 8.10.0 $ npm i semantic-ui npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

When tapping on grid items in the Safari browser using React Material-UI, they mysteriously switch positions

I've encountered an issue with grid Items in my React MATERIAL-UI project, specifically in the Safari browser. The problem does not occur in Chrome or Firefox. Within the grid, there are checkboxes that move from one place to another when clicked, a ...

Exploring the utilization of type (specifically typescript type) within the @ApiProperty type in Swagger

Currently, I am grappling with a dilemma. In my API documentation, I need to include a 'type' in an @ApiProperty for Swagger. Unfortunately, Swagger seems to be rejecting it and no matter how many websites I scour for solutions, I come up empty-h ...

Revise the line graph

Currently, I am utilizing dimple js and have a line chart code. However, there seems to be an issue with the event I set up - whenever a button is clicked, the chart should redraw using chart.draw(), but this function doesn't seem to work. Any insight ...

What is the method for identifying modules that rely on a specific module?

Is it possible to view all dependencies modules of a specific module, similar to this: npm-remote-ls <module-name> But how can we see the modules that depend on a particular module? Any help would be appreciated. Thank you. ...

Is there a way to retrieve and store a JSON object from a URL using JavaScript and jQuery?

I have a PHP page that is returning a JSON object in the correct format, like this: [ { "name":"Users", "parent":"null", "children":[ { "name": "adsd", "parent": "Users", "children": [] } , { "name": "ca", "p ...

What is the process for sending a message from the internet to a mobile device?

We are currently in the process of developing a website that sends SMS alerts to users for specific services, however I am struggling to set up a script that can perform this function. If anyone has any suggestions or recommendations for a solution, pleas ...