Adding dynamic color changes to points using three.js

I'm trying to change the colors of these points by randomly turning some of them white every 0.5 seconds.

  this.geom = new THREE.SphereBufferGeometry(6, 350, 90);
  this.colors = [];

  this.color = new THREE.Color();
  this.colorList = ['red','blue','pink'];
  for (let i = 0; i < this.geom.attributes.position.count; i++) {
    this.color.set(this.colorList[THREE.Math.randInt(0, this.colorList.length - 1)]);
    this.color.toArray(this.colors, i * 3);
  }
  this.geom.addAttribute('color', new THREE.BufferAttribute(new Float32Array(this.colors), 3));

In order to update the colors without reloading all the points and causing the page to freeze, I am calling a function in the animate loop. I only want about 30 of the points to randomly turn white. How can I achieve this efficiently?

this.colorList = ['white', 'pink', 'blue', 'red'],

updateColor() {
  for (let i = 0; i < this.geom.attributes.position.count; i++) {
    this.color.set(this.colorList[THREE.Math.randInt(0, this.colorList.length - 1)]);
    this.color.toArray(this.colors, i * 3);
  }
  this.geom.attributes.color.needsUpdate = true;
  this.geom.addAttribute('color', new THREE.BufferAttribute(new Float32Array(this.colors), 3));
}

Answer №1

Exploring a possible approach:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 12);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const controls = new THREE.OrbitControls(camera, renderer.domElement);

const geometry = new THREE.SphereBufferGeometry(6, 350, 90);
const colors = [];

const color = new THREE.Color();
const colorList = ['red', 'purple', 'pink'];
for (let i = 0; i < geometry.attributes.position.count; i++) {
  color.set(colorList[THREE.Math.randInt(0, colorList.length - 1)]);
  color.toArray(colors, i * 3);
}
geometry.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));
geometry.addAttribute('colorBackup', new THREE.BufferAttribute(new Float32Array(colors), 3));

const points = new THREE.Points(geometry, new THREE.PointsMaterial({
  vertexColors: THREE.VertexColors,
  size: 0.125
}));
scene.add(points);

const usedIndices = [];
const numPoints = 300;

function modifyColors() {

  for (let i = 0; i < usedIndices.length; i++) {
    const index = usedIndices[i];
    geometry.attributes.color.copyAt(index, geometry.attributes.colorRestore, index); // revert the color of a point
  }

  for (let i = 0; i < numPoints; i++) {
    const index = THREE.Math.randInt(0, geometry.attributes.color.count - 1);
    geometry.attributes.color.setXYZ(index, 1, 1, 1); // set point's color to white
    usedIndices[i] = index; // save the index of the point
  }

  geometry.attributes.color.needsUpdate = true;
}

setInterval(modifyColors, 500);

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

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 jQuery function text().replace('','') is failing to work properly

After spending countless hours attempting to remove a text string that I previously appended, I am still struggling. The script I have is responsible for managing an accordion and unfortunately contains some redundant text. My goal is to add and remove th ...

Adequate parameters are necessary for an express callback function beyond just (req, res)

Working on my express app, I've come across a requirement where only (req, res, next, err) can be passed into the callbacks. This is what I had that worked. function listEvents(auth, req, res, email, authURL = ""){ ... var calendar = google.calendar ...

Using MUI Select with Array of Objects for values - Learn how to deselect a predefined state

I have a list of objects structured like this: [ { _id: "6311c197ec3dc8c083d6b632", name: "Safety" }, ........ ]; These objects are loaded as Menu Items options for my Select component: {categoryData && c ...

Update the formatting of the dates in the dateRangePicker

Utilizing a dateRangePicker, I am receiving dates in the format "mm-dd-yyyy". Below is my HTML code: <input type="text" name="TextDate" value="10/24/1984" /> Here is the script being used: <script> $(function() { $(&apos ...

Tips on incorporating the vue package

I recently started using Vue and decided to incorporate a plugin called vue-toastr. I'm attempting to integrate it with Laravel, which already has Vue set up with the plugin. Unfortunately, I keep encountering an error that says "TypeError: Cannot rea ...

"Error message: The server tag within the OnClientClick attribute is not properly formed

In the HTML code, there is the OnClientClick attribute set to evaluate if IsActive is true before triggering a confirmation message for removing the control from Brand-Mappings. Unfortunately, this is currently causing a server tag not formed error. Any a ...

Tell webpack to exclude a specific import

Currently, I am in the process of developing a desktop application using ElectronJS and ReactJS. To bundle the renderer process that utilizes JSX, I have opted to use webpack. An issue arises when attempting to import anything from electron into the rend ...

The impact of a variable in a function with XMLHttpRequest

How does the XMLHttpReqeust variable impact the functionality of the following code snippets? function getHTTPObject() { if (typeof XMLHttpRequest == "undefined") { XMLHttpRequest = function () { try { return new Ac ...

The latest update to the Server Stats code mistakenly changes the channel to "undefined" instead of displaying the total number

I've been working on a private bot for a specific server that displays server statistics and more. However, I've encountered an issue where every time a user joins or leaves the guild, the bot updates a channel with 'undefined' instead ...

Tips for automatically sending data back to the server every two seconds using ASP.NET Web Form

My Textbox looks like this : <asp:TextBox runat="server" ID="Text1"></asp:TextBox> I need my Textbox to send data back to the server every two seconds using setInterval in JavaScript. ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...

Is there a way to retrieve the JavaScript variable name for a rhandsontable displayed in a Shiny application?

My project involves using the rhandsontable package to generate dynamic tables within a Shiny app. I am in need of a solution that allows me to select certain cells programmatically, triggered by specific user interactions. Unfortunately, I have not been ...

Tips for waiting for a Promise to resolve before returning a new Promise

In the process of developing a web application tailored for crafting retail signage, I have integrated Firestore to manage pertinent information about these signs. One specific functionality I am working on is enabling users to effortlessly remove all exis ...

Ember 2: Display a loading message only if the IDs were part of the initial response

I frequently use the following code snippet in my projects: {{#each model.posts as |post|}} <div>post.title</div> {{else}} <div>Loading the posts...</div> {{/each}} However, I sometimes face uncertainty regarding whether t ...

Navigate through the Jquery slider by continuously scrolling to the right or simply clicking

Is there a way to prevent my slider from continuously scrolling? I think it has something to do with the offset parameter but I'm having trouble figuring it out. Any assistance would be greatly appreciated. var $container = $(container); var resizeF ...

How to disable a specific array of dates in Ant Design range picker

Is there a way to block dates prior to the current date and specify certain dates that should also be disabled on the calendar? For example, I need to prevent selection of: Today: 2018-07-30 Dates to disable: [2018-08-10, 2018-08-12, 2018-08-20] When t ...

Leverage API providing HTML and JavaScript exclusively using PHP script

Seeking a way to automate the conversion process from HTML to PNG using a PHP script with a REST API. The website only provides an example using HTML and JavaScript, allowing users to upload an HTML file for conversion. My PHP script currently generates H ...

Completed processing graphical event layer

I am utilizing the Google Maps API v3 to build a map with multiple layers that are loaded upon user request. The layers are loaded in Geojson format using the following code: function getgeojson(json) { proplayer = new google.maps ...

Loading the Facebook JavaScript SDK asynchronously using React and Redux

I have a process that involves loading a JavaScript SDK, which looks like this: class Facebook{ constructor(){ window.fbAsyncInit = () => { FB.init({ appId : 'myappID', ...

Using a semicolon at the end of the line is considered a favorable practice when writing ES6 code in Babel

After browsing through various tutorials on the internet that utilize redux and react, I came across a common trend of omitting semicolons in ES6 code when using Babel. For instance, some examples neglect to include semicolons at the end of import or expo ...