A guide to setting individual colors for each point in ThreeJS

Currently, I am experimenting with ThreeJS to generate a point cloud. My goal is to assign a distinct color to each individual point within the cloud based on its position. How can I go about setting specific colors for each vertex in the geometry and subsequently changing those colors as needed?

geometry = new THREE.Geometry();

for (i = 0; i < particleCount; i++) {

            var vertex = new THREE.Vector3();
            vertex.x = Math.random() * 2000 - 1000;
            vertex.y = Math.random() * 2000 - 1000;
            vertex.z = Math.random() * 2000 - 1000;

            geometry.vertices.push(vertex);
        }

colors = [0xff0000, 0x0000FF, 0x00FF00, 0x000000]
size = 0.5

            material = new THREE.PointsMaterial({
                size: size,
                color: colors[0]
            });

particles = new THREE.Points(geometry, material);

scene.add(particles);

Answer №1

Commencing with r125, the use of THREE.Geometry has been deprecated and is no longer part of the core functionality. It is strongly advised to utilize THREE.BufferGeometry instead.

To assign a color per vertex, it is necessary to include an additional buffer attribute that stores the vertex colors. Additionally, remember to set the material property vertexColors to true.

let camera, scene, renderer;

let points;

init();
animate();

function init() {


  camera = new THREE.PerspectiveCamera( 27, window.innerWidth / window.innerHeight, 5, 3500 );
  camera.position.z = 2750;

  scene = new THREE.Scene();
  scene.background = new THREE.Color( 0x050505 );
  scene.fog = new THREE.Fog( 0x050505, 2000, 3500 );

  //

  const particles = 500000;

  const geometry = new THREE.BufferGeometry();

  const positions = [];
  const colors = [];

  const color = new THREE.Color();

  const n = 1000, n2 = n / 2; // particles spread in the cube

  for ( let i = 0; i < particles; i ++ ) {

    // positions

    const x = Math.random() * n - n2;
    const y = Math.random() * n - n2;
    const z = Math.random() * n - n2;

    positions.push( x, y, z );

    // colors

    const vx = ( x / n ) + 0.5;
    const vy = ( y / n ) + 0.5;
    const vz = ( z / n ) + 0.5;

    color.setRGB( vx, vy, vz );

    colors.push( color.r, color.g, color.b );

  }

  geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
  geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );

  //

  const material = new THREE.PointsMaterial( { size: 15, vertexColors: true } );

  points = new THREE.Points( geometry, material );
  scene.add( points );

  //

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  //

  window.addEventListener( 'resize', onWindowResize );

}

function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize( window.innerWidth, window.innerHeight );

}

//

function animate() {

  requestAnimationFrame( animate );

  render();

}

function render() {

  const time = Date.now() * 0.001;

  points.rotation.x = time * 0.25;
  points.rotation.y = time * 0.5;

  renderer.render( scene, camera );

}
body {
  margin: 0;
 }
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f88c908a9d9db8c8d6c9cacdd6ca">[email protected]</a>/build/three.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 Kendo Date Picker is failing to update properly when the k-ng-model is modified

I am facing an issue with my code involving two date pickers and one dropdown list. I want the date pickers to change based on the selected item from the dropdown list. Here is the relevant portion of my code: $scope.toolbarOptions = { i ...

Alerts in online software when there is a modification in the database

I am working on a project to create a web application that needs to display notifications, like the ones you see on Facebook, whenever there is a new update in the database. I could use some assistance with implementing this feature. Are there any third- ...

Disable Vue click event based on a condition

One issue I encountered was that even though I successfully disabled the document body scroll when my mobile nav was open, the overflow hidden feature was not being removed when a user clicked a link to another route or page. To address this, I implement ...

What is the best way to initiate an image loop with the click of a button?

<p align="center"> <button onclick="slideit()">Run the loop</button> <!-- Start Weather Image Loop --> <img src="firstcar2.gif" name="slide" width="900" height="500" /> <script type="text/javascript"> <!-- var ...

Why isn't the program recording user input in the console when the form is submitted?

Can someone please advise me on how to get the program to print the user's input values to the console when they click the "Sign up now" button? ...

Conquering Challenges Across Multiple Disciplines

Is there a solution to solving the cross domain issues that arise when trying to fetch data from a different web server on the client-side, in violation of the Same Origin policy? ...

Encountering an "Unsupported Media Type" error while attempting to generate an Hpalm defect through the rest api

I have been attempting to create a defect through the hpalm rest api, but I keep encountering a "415 Unsupported Media Type" error. Here's what I've done so far: var postOptions = { jar: cookies, accept: 'application/json', ...

A Kendo editor necessitates the use of Kendo JavaScript specifically designed for Angular

Can someone provide guidance on the necessary Kendo libraries for implementing the Kendo editor in AngularJS? The tutorial site suggests that "kendo.all.min.js" is required, but I am hesitant to use it due to its resource-heavy nature. Any assistance wou ...

How to retrieve a variable from an object within an array using AngularJS code

I recently started learning TypeScript and AngularJS, and I've created a new class like the following: [*.ts] export class Test{ test: string; constructor(foo: string){ this.test = foo; } } Now, I want to create multiple in ...

A guide on retrieving data with JSONP, Ajax, and jquery

I am having trouble retrieving data from an API using JSONP. I enter an ISBN number into an input box and attempt to fetch the data, but I keep encountering an error message stating "Cannot read property 'title' of undefined". Can anyone assist m ...

How to Utilize Ionic/Angular Diagnostic.requestRuntimePermission (Incomplete Documentation)

My current application requires permission for Camera, AudioInput (Microphone), and Storage. Since Android 6, it has become necessary to request these permissions at runtime in order to gain access. To accomplish this, the Ionic 2 Cordova Plugin "Diagnosti ...

What is the timing for when the SignalR connection is terminated from the browser?

Currently, I am developing a chat application using SignalR 2.0, like many others in the same field. In my Win8.1 application, when the user closes the application, the hub receives the OnDisconnected event and removes the user from the list on the hub. A ...

if the checkbox is selected, navigate to the displayed section

In my scenario, I have a total of 5 checkboxes and corresponding to each checkbox, there are 5 div elements. The functionality that I need is that when a checkbox is checked, the associated div should be displayed; otherwise, it should be hidden. The check ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Searching for a point within a specified range using Sequelize

I have a model called Location with a field named coordinates of type geometry. I'm looking to create a function that takes in latitude, longitude, and radius as parameters, and returns all locations within that radius (in meters). I attempted to foll ...

Having trouble sending an array from Flask to a JavaScript function

As a newcomer to web development and JavaScript, I'm struggling to pass an array from a Flask function into a JavaScript function. Here's what my JS function looks like: function up(deptcity) { console.log('hi'); $.aja ...

How can I combine jQuery "this" along with a CSS selector?

Currently, I am working on a script that will allow me to toggle the visibility of a section within a div. I have three of these divs with hidden sections and I am trying to find a way to control all three using a single function. This is what my code loo ...

Only a single element in the array is being pushed by the JavaScript code, not all elements

Having an issue with my script where it is only returning one element out of a class that has 10 elements. Can anyone help me pinpoint the problem? `function() { var vins = document.querySelectorAll('.dws-vehicle-listing-item-field.dws-vehicle-field- ...

Verify if the element in the array is set to true

Using a simple boolean in a condition is straightforward : var running = true; if(running) {/*do something*/} But what about using a boolean array? Can it be done like this: var running = [false,false,true,false]; if(running[]){/*do something*/} Curren ...

Display or Hide certain Items/Elements depending on the chosen Category

I have multiple images within a div, each image belonging to a specific category. I want to display only the images from a selected category and hide all others. Initially, all images are in the category all. When selecting the category blue, for example, ...