Combining variously colored meshes

Utilizing Three.js version 75

I am attempting to showcase cubes that alter color based on an integer value ranging from green to red. I have experimented with various methods but have hit a roadblock. Unfortunately, both cubeMat.material.color.setRGB and creating a new Three.Color do not seem to be effective. It's worth noting that I combine all geometries at the end for a single draw call, and I'm hoping this isn't causing the problem.

[UPDATE] I have verified that the RGB values are correctly set using getStyle; however, they are not rendering as expected. Each stack of cubes should exhibit different colors.


function colorData(percentage){
    var rgbString = "",
        r = parseInt(percentage * 25.5),
        g = parseInt(((percentage * 25.5) - 255) * -1),
        b = 0;

    rgbString = "rgb("+r+","+g+",0)";
    return rgbString;
}

...
var position = latLongToSphere(objectCoord[1], objectCoord[0], 300),
            rgb = colorData(objectMag),
            cubeColor = new THREE.Color(rgb),
            cubeMat = new THREE.MeshBasicMaterial({color: cubeColor}),
            cubeHeight = objectMag * 175,
            cubeGeom = new THREE.BoxGeometry(3,3,cubeHeight,1,1,1),
            cube = new THREE.Mesh(cubeGeom, cubeMat);

        // set position of cube on globe, point to center, merge together for one draw call
        cube.geometry.colorsNeedUpdate = true;
        cube.position.set(position.x, position.y, position.z);
        cube.lookAt(lookCenter);
        cube.updateMatrix();
        console.log(cube.material.color.getStyle());
        geom.merge(cube.geometry, cube.matrix);

Answer №1

If you want to merge geometries in order to render with a single draw call and material, but still have each merged geometry display a different color, you can achieve this by setting vertexColors (or faceColor) in your geometry. Follow this pattern:

// Create the geometry
var geometry = new THREE.Geometry();

// Loop to create and merge multiple box geometries
for ( var count = 0; count < 10; count ++ ) {

    var geo = new THREE.BoxGeometry( 5, 5, 5 );

    // Translate the geometry randomly
    geo.translate( THREE.Math.randFloat( - 5, 5 ), THREE.Math.randFloat( - 5, 5 ), THREE.Math.randFloat( - 5, 5 ) );

    // Generate a random color for each face of the geometry
    var color = new THREE.Color().setHSL( Math.random(), 0.5, 0.5 );

    // Assign the color to each face's vertex colors
    for ( var i = 0; i < geo.faces.length; i ++ ) {

        var face = geo.faces[ i ];
        face.vertexColors.push( color, color, color ); // All faces have the same color in this case

    }

    // Merge the current geometry into the main geometry
    geometry.merge( geo );

}

When specifying the material for the merged geometry, ensure to set vertexColors like this:

// Define the material
var material = new THREE.MeshPhongMaterial( {
    color: 0xffffff,
    vertexColors: THREE.VertexColors // Use THREE.FaceColors if defined instead
} );

Your geometry will now be rendered with a single draw call. Confirm this by checking the console with renderer.info. The value of renderer.info.render.calls should be 1.

This code is compatible with three.js r.75

Answer №2

The function cubeMat.material.color.setRGB may not be effective as it seems to call the material twice (cubeMat and material). You could consider using the following code snippet instead:

cube.material.color.setRGB( value, value, value );

Answer №3

It turns out that when you combine the geometry, the materials cannot have separate colors. I learned that I needed to define the color of each cube's face before merging them.

For more information on this topic, please visit:

Changing material color on a merged mesh with Three.js

Three.js materials of different colors are displaying as one color

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

Creating artwork using a "graphite drawing tool" on a blank canvas

I created a script that draws a series of lines on a canvas, giving it a sketch-like appearance. However, I have encountered two issues with the script. Firstly, why is the y value appearing to be twice as much as it should be? Secondly, why is the line w ...

Perform an API request to retrieve text content

I am currently utilizing Spark AR to develop a straightforward effect that retrieves text from an API and showcases it. Below is the code I am working with: const Scene = require('Scene'); const Diagnostics = require('Diagnostics'); c ...

Using jQuery, you can utilize the $.when() function with both a single deferred object and an

In my current jquery setup, I am working with two variables. trackFeatures - representing a single ajax request, and artistRequests - an array of ajax requests. I am looking for a way to create a condition that triggers when both trackFeatures and artist ...

Is it possible to propagate hover events across multiple layers?

I'm encountering an issue with my interactive background and overlay. Currently, when a user hovers over these elements, only the hover event for the overlay is triggered. Is there a way to set it up so that both elements trigger hover events simultan ...

Designing versatile buttons with HTML

When accessing the website on a phone, I have trouble seeing and tapping on these two buttons because they are too far apart. I would like to change it so that once a file is selected, the 'choose file' button will be replaced by the upload butto ...

PHP AJAX Serial Port Text Input Command

Recently, I've been delving into the world of PHP and AJAX. Despite being a newcomer, I've managed to grasp some basic concepts over the past few weeks. Along the way, I've relied on various posts from this platform for guidance, so when a p ...

How can Ext JS 6.2 automatically expand the East panel when the West panel is triggered?

In my Ext JS v6.2 Grid application, I am faced with the task of ensuring that if the WestRegion panel is closed, the EastRegion panel should open automatically, and vice-versa. Being new to Ext JS, I initially attempted to achieve this using jQuery. Howeve ...

Performing two simultaneous AJAX requests using tokeninput

I've been playing around with the tokeninput plugin and it's been working really well for me. However, I recently came across a new requirement - I need to make two separate ajax calls on the same input bar. Situation: My input bar is as follows ...

What is the best way to reference a dynamic ID in JavaScript when clicking for an action on a different

Here is my HTML code snippet: <table> <tr> <td> @Html.DropDownList("Statues", (SelectList)ViewBag.UserType, string.Empty, new { @class = "NewIDCn",@id = "name1" }) </td> <td> ...

Modify my JavaScript array by separating each element with a comma

JavaScript or jQuery is what I'm comfortable using Including an additional database table column has resulted in: 122461,4876192 Now there are 2 records So it displays like this: https://i.sstatic.net/7mjFY.png $.each(alldata.Data, function (in ...

Converting an array into a duplicate key object using Node.js - Learn how!

I am looking to transform an array into a duplicate key object in Node.js. Here is the array data I have: { "name" : "ashesh", "address_data" : [ { "city" : "Mumbai", "pincode": "400097" }, { ...

Tips for sending a spring form as a parameter in an Ajax request using a JavaScript function

I have a form in Spring with two buttons on a JSP file. <input type="button" onclick="saveFormActions(this.form)" class="btn primary publish border16" id="saveBtn" value="Save"/> <input type="submit" class="btn primary publish bor ...

What is the process for customizing the color and thickness of the active tab inkBarStyle in React Material-UI?

Check out this inquiry: How can I change the color of the active tab in MUI? And for a potential solution, have a look at this response: The provided answer seems to be effective: <Tabs inkBarStyle={{background: 'blue'}}>... However, I a ...

Variations in performance when utilizing document.getElementById(id), $(id), and containerElement.find(id)

Imagine there is a container element on a webpage surrounded by other elements that make up the page layout and navigation. Inside this container, there is a substantial amount of content. When working with JavaScript, I need to locate and manipulate spec ...

Tips for ensuring that the "this" in React ES6 static method is bound to the lexical scope

Currently in React with ES6 via babel, my goal is to develop a static method that can update the state of the Component it belongs to by accepting an object as an argument. However, I'm facing an issue where "this" is not bound to the lexical scope. ...

"Troubleshooting a glitch encountered while making an invokeAPI call with Azure Mobile

Working on integrating my Angular App with Azure Services as the back end. Initially, I used the standard $http call: $http({ method: 'POST', url: "https://services.example.com/Api/myApi", headers : { "Content-Type" ...

I am facing conflicts between vue-tsc and volar due to version discrepancies. How can I resolve this problem?

My vsCode is alerting me about an issue: ❗ The Vue Language Features (Volar) plugin is using version 1.0.9, while the workspace has vue-tsc version 0.39.5. This discrepancy may result in different type checking behavior. vue-tsc: /home/tomas/Desktop/tes ...

The functionalities of $scope and this in AngularJS

Currently, I am developing a small application using angularjs. In this project, I am trying to implement a feature that involves deleting a contact. The functionality itself works perfectly fine, however, I am encountering an issue where the 'this.op ...

Having trouble retrieving a JSON Element in JavaScript using the Object's property

I am having trouble retrieving a specific JSON element from the following JSON structure: { "ACTION": "AA", "MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01" } Even though I receive the data in JSON format, attempting to access data.ACTION or d ...

Avoiding Repetition in Vue.js with Vuex

When approaching repetitions in my code with Vue.js and Vuex, I often encounter similar mutations that need to be handled separately. For instance, I have mutations for both Services and Materials that share a lot of similarities. The first mutation is ...