Implementing diverse color gradients to individual vertices within a geometry using three.js

My goal is to enhance the functionality of this code snippet so that when the button is clicked, the selected mesh's neighborhood vertex is highlighted with a gradient effect.

function addSphere()
{
var position = new Array();
var notAboveGround = true;
while(notAboveGround){
    position[0]=Math.random()*floorSide-floorSide/2;
    position[1]=Math.random()*floorSide-floorSide/2;
    position[2]=Math.random()*floorSide/5;
    var sphereSide = Math.random()*floorSide/12+floorSide/50;
    //alert("cubeSide="+cubeSide);
    if(position[2]-sphereSide>0){
        notAboveGround = false;
    }
}

var faceColorMaterial = new THREE.MeshLambertMaterial( 
{ color: 0xffffff, vertexColors: THREE.FaceColors,shading:THREE.FlatShading,polygonOffset: true,polygonOffsetUnits: 1,polygonOffsetFactor: 1} );

// var sphereGeom= new THREE.SphereGeometry(sphereSide,0);
var sphereGeom = new THREE.SphereGeometry(80,10,10);
for ( var i = 0; i < sphereGeom.faces.length; i++ ) 
{
    face = sphereGeom.faces[ i ];   
    face.color= baseColor;      
}
var sphere= new THREE.Mesh( sphereGeom, faceColorMaterial );
sphere.position.set(0, 150, 0);
// creates a wireMesh object
wireSphere = new THREE.Mesh(sphereGeom, new THREE.MeshBasicMaterial({ color: 0x116611, wireframe: true }));

scene.add(sphere);
// wireMesh object is added to the original as a sub-object
sphere.add(wireSphere );

targetList.push(sphere);

}

I am attempting to implement the code examples provided by Mr. Stemkoski from this link:

// this material causes a mesh to use colors assigned to vertices
var vertexColorMaterial = new THREE.MeshBasicMaterial( { vertexColors: THREE.VertexColors } );

var color, point, face, numberOfSides, vertexIndex;

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

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

// first, assign colors to vertices as desired
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; // use this array for convenience
}

// copy the colors to corresponding 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 );

However, I am facing challenges with the JavaScript closer property and uncertain about how to proceed from here. Any suggestions or guidance would be greatly appreciated. Thank you!

Answer №1

To inject some vibrant color into the vertex, you'll need to dive into the world of the vertexColors array found within the face. Although the example code you shared follows this pattern, you seem to be missing a critical piece within your own implementation. To remedy this, consider incorporating the following snippet:

var numberOfSides, j, vertexIndex;

for ( var i = 0; i < sphereGeom.faces.length; i++ ) 
{
    face = sphereGeom.faces[ i ];   
    face.color= baseColor;      
    numberOfSides = ( face instanceof THREE.Face3 ) ? 3 : 4;
    for( j = 0; j < numberOfSides; j++ ) 
    {
        vertexIndex = face[ faceIndices[ j ] ];
        face.vertexColors[ j ] = sphereGeom.colors[ vertexIndex ];
    }
}

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

What do you notice about interactions involving 'input type=text' in HTML and JavaScript?

When a new binding is created for the value property on an input, any manual modifications by the user no longer update the value. What happens when the binding is altered? Does regular user interaction involve key press listeners? I've modified the ...

Looking for a simple method to display a popover using conditional if/else statements?

On my website, I am utilizing JavaScript to determine the user's Facebook status. This includes checking if the user is already logged in and has allowed our app, if they are logged in but haven't authorized our application, or if they are not lo ...

Which is more effective: using the try-catch pattern or the error-first approach

My main focus is on node.js and express.js, although I am relatively new to JavaScript overall. When it comes to error handling, the official recommendation is to use the try-catch pattern. However, some developers argue in favor of sticking with the tradi ...

Passing PHP value from a current page to a popup page externally: A guide

I'm currently facing an issue at work where there is a repetitive button and value based on the database. I need to extract the selected value from the current page into a pop-up page whenever the corresponding button is clicked throughout the repetit ...

Dealing with AJAX error in pure JavaScript

I have been attempting to address AJAX errors using the code below, but unfortunately, it does not seem to be effective. function ajaxPost(url, data, success, error) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () ...

Error message: It seems the spatial reference for this ESRI object is missing

Currently, I am utilizing Esri GIS to load the center location from an address. However, I am encountering an issue as I am using a geocoder from Google to obtain longitude and latitude, which is resulting in the following error message: TypeError: this.s ...

Creating a texture in Three.js using an image file

Having some difficulty with creating a texture from an image file using Three.js. Currently, attempting to create a mesh using the following function: var image = document.createElement('img'); image.src = imageFile; var texture = ne ...

Tips on customizing the appearance of React rendering components

<div> <h3>{this.props.product.name}</h3> <h3>{this.props.product.code}</h3> {this.renderColors()} <article> <div da ...

Is it possible to repeat this action by swiping to the left?

I'm currently developing an app in PhoneGap and retrieving information using JSON. My goal is to trigger this function again with Ajax when I slide left. This is the code I have so far. Thank you to everyone for your assistance. $(document).ready( ...

Tally of number series in an array

If my array looks like [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10] How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions. In this example, the output would be 2 because there are 2 s ...

Obtain the non-dynamic route parameters as query parameters in Next.js

I need help figuring out how to extract specific query parameters from a URL in my component. I want to exclude dynamic route parameters, such as {modelId}. For example, if the URL is /model/123456?page=2&sort=column&column=value, I only want to re ...

Resetting the randomness in a function within a sudoku generator implemented in JavaScript

I'm in the process of creating a unique Sudoku generator that incorporates randomness into its design. Within my code, there's a particular function responsible for generating the Sudoku puzzles. The issue I'm encountering is the inability t ...

What is the proper way to utilize the name, ref, and defaultValue parameters in a select-option element in React Meteor?

I recently developed a Meteor project using ReactJS. I have a Create/Edit page where I use the same input field for various form elements. Here is an example of code snippet that I currently have: <FormGroup> <ControlLabel>Province</Control ...

Assigning numerical ratings to a web-based questionnaire in HTML

In my questionnaire, I have radio buttons and checkboxes that need to be graded. The format of the input elements looks like this: <input type="radio" name="1" value="Yes" onclick="document.getElementById('pls').setAttribute('requi ...

Numerous Kendo windows are layered on top of each other, yet the text divisions within them remain distinct

I am currently working on a project that involves laying out multiple Kendo windows in rows. Specifically, I need to display 4 windows in each row and have them shift left when closed. My framework of choice is Bootstrap 3. Everything works as expected w ...

The unique identifier for retrieving an object from the database is dynamic and subject to change with each

Click here for image description I am currently building an app using Express and Mongoose MongoDB. However, when I try to access /musics/:id to go to the details page, the app redirects me to the correct page but crashes because the id is being changed. ...

Why is it impossible for me to show the title "individual name:"?

<p id="display1"></p> <p id="display2"></p> var player1= { alias: 'Max Power', skills: ['shooting', 'running'] }; $("#display1").append( "<br/>" + "player alias :" + player1.alia ...

RequestDispatcher.forward() does not work when servlet is invoked through an Ajax POST request

My login page involves user authentication through the firebase and sending the request to a servlet. When I click the submit button with correct credentials, the firebase authentication works, the servlet is called but an error is displayed in the browser ...

Vue.js is experiencing issues with updating attributes within nested v-for loops

Exploring the realm of vue.js and react, I am currently in the process of adapting a basic editable HTML table example found in a React book to further my understanding of Vue. Here is a breakdown of what occurs within the code: User clicks on a td elem ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...