Customizing Sphere Hues Individually in three.js

Within my scene, a unique arrangement of 7 spheres creates a flower petal formation. The setup includes 6 spheres around the perimeter and one sphere at the center. I aimed to randomize the color of each sphere individually. Below is the code snippet utilized in this attempt:

function changeSphereColors() {
    var hex, color, len = spheres.length;
    var change = function(i) {
        var hex = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});
        color = new THREE.Color(hex);
        spheres[i].material.color = color;

    }
    for (var i=0; i<len; i++) {
        change(i);
    }
}
var render = function() {
    requestAnimationFrame(render);
    rotateSpheres();
    var num = Math.random();
    if (num<0.1) {
        changeSphereColors();
    }
    renderer.render(scene, camera);
}
render();

An array named spheres holds the 7 spheres within the scene. The intention was to assign a distinct random hexadecimal color to each sphere by iterating through them. Curiously, instead of displaying 7 spheres with varied colors, all spheres appear in the same color.

Upon examination of the outputs to verify individual colors and loop functioning correctly, everything appeared operational. Each iteration generated a unique hex color and successfully applied it to the respective sphere.

This leads to the question: Why do all spheres share identical colors?

Answer №1

It's possible that the similarity in appearance is due to them using the same material. Try creating a distinct material for each object.

For instance, consider this scenario where I have 3 spheres - two of them sharing one material and one having its own. Changing the color of one sphere affects the other when they share the same material:

var shape = new THREE.SphereGeometry(3, 50, 500, 0, Math.PI * 2, 0, Math.PI * 2);

var substance1 = new THREE.MeshBasicMaterial();
var substance2 = new THREE.MeshBasicMaterial();

var orb = [new THREE.Mesh(shape, substance1), new THREE.Mesh(shape, substance1), new THREE.Mesh(shape, substance2)];

scene.add(orb[0]);
scene.add(orb[1]);
scene.add(orb[2]);    

var code = "0x" + "000000".replace(/0/g, function(){return (~~(Math.random()*16)).toString(16);});        
orb[0].material.color.setHex(code);

code = "0x" + "000000".replace(/0/g, function(){return (~~(Math.random()*16)).toString(16);});        
orb[2].material.color.setHex(code);

// Both orb[0] & orb[1] will now display the same color, although it wasn't set explicitly for orb[1].
// Orb[2] retains its unique color.

Experiment with the example here

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

The website is experiencing functionality issues with Ajax

On my personal website, I am trying to add a simple ajax server clock in the header section but unfortunately it is not appearing as expected. Here's the snippet of Javascript code that I am using: var httpxml; try { // Firefox, Opera 8.0+, Safari ...

Generating dynamic arrays in JavaScript

View the working code here: http://jsfiddle.net/sXbRK/ I have multiple line segments with unique IDs, and I know which ones intersect. My goal is to create new arrays that only contain the IDs of the overlapping line segments. I do not need the IDs of l ...

Learning React: Error - Unable to access the 'data' property when it is null

Currently, I am learning React by following a tutorial available at this link: http://facebook.github.io/react/docs/tutorial.html Specifically, I am focusing on the section related to fetching data from the server, which can be found here: http://facebook ...

Issue with Javascript form submission leading to incorrect outcomes

When setting the form action to a text retrieved from the database with an ID, I encountered a problem where it always displays the first ID even when clicking on text holding ID=2. Upon checking the page source, the correct IDs are shown for all texts. B ...

Using TypeScript, implement a function that is called when a React checkbox's state changes to true

Currently, I am experimenting with the react feature called onChange. My goal is to update local data by adding a value when a checkbox is selected. Conversely, when the checkbox is unselected, I just want to display the original data. However, I find that ...

Trouble locating DOM element in Angular's ngAfterViewInit()

Currently, I am attempting to target a specific menu item element within my navigation that has an active class applied to it. This is in order to implement some customized animations. export class NavComponent implements AfterViewInit { @ViewChild(&a ...

In angular.js, repeating elements must be unique and duplicates are not permitted

My view controller includes this code snippet for fetching data from an API server: $scope.recent_news_posts = localStorageService.get('recent_news_posts') || []; $http({method: 'GET', url: 'http://myapi.com/posts'} ...

How can I use PHP to transform a JSON object containing xy coordinates into an image?

What is the best way to convert a JSON object containing xy coordinates into an image (PNG or JPG) using PHP or JavaScript? ...

What is the best way to send a JavaScript array to a Perl script using AJAX?

Is it possible to convert a JavaScript array passed via AJAX into a Perl array? Accessing in Perl: @searchType = $cgi->param('searchType'); print @searchType[0]; Result: employee,admin,users,accounts It appears that the first value in the ...

Utilizing NextJS to retrieve cookie data within React components

Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...

Steps to gather all the images within a directory

Take a look at this demo When you click on the "next" button, new images are loaded from the internet. In my application, all the images are stored in the img/image folder with names like 1.jpg, hi.png, etc. My question is, how can I display these image ...

What causes the jQuery mouseenter events to be activated in a random sequence?

I currently have a setup of 3 nested divs, resembling the concept of a Matryoshka doll. Each div has a mouseenter event function bound to it. When moving the mouse slowly from the bottom and entering layer three, the events occur in the following sequence ...

Error encountered: index.html:17 - An InvalidStateError was thrown when attempting to execute the 'send' function on the XMLHttpRequest object. The object's state must be OPENED in order to send the Ajax request

When attempting to run index.html on a local host with xampp, an error is encountered: index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax @ index.html: ...

Integrating a feature for displaying No Results Found

I am struggling to modify a script for auto-completing search fields. My goal is to include a "No Results Found" option along with a hyperlink when no matching results are found. I'm having difficulty figuring out how to add an else statement to displ ...

Show just three items simultaneously

I am currently working on a quote generator and I want to add a feature that allows me to display a specific number of quotes at a time. I attempted to use map for this purpose, but encountered an error stating it's not a function. Currently, the gene ...

Can someone share with me the best practices for implementing @HostListener within a method in my Angular 16 project?

Currently, I've been involved in developing a Single Page Application using Angular 16, TypeScript, and The Movie Database (TMDB). My task at hand is to implement the "infinite scroll" functionality on a particular component. To achieve this, I have ...

The $.post method is malfunctioning

I am experiencing an issue where the onchange function is working properly, but the $.post function is not functioning as expected. Below is the HTML code snippet: <input type="checkbox" id="chk" value="3" onchange="checkradio(this.value)"/> Here ...

ng-model assigns the value to the select

Below is the angularjs directive I have created: dicApp.directive('listpanel', function ($resource) { return { restrict: 'E', template: '<select ng-model="selectedDictionary" ng-change="listChange()">&apo ...

Navigate through each of the pictures within the folder and encode them into base64

I'm currently working on a project where I need to convert images in a folder to base64 and then store them in MongoDB. At first, I successfully converted a single image: var filename = '1500.jpg'; var binarydata = fs.readFileSync(filename ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...