Create a trio of particles all in the same color spectrum

Greetings! I have scoured the internet but have not come across any solutions. I am attempting to create a globe made of particles in three different colors - pink, dark pink, and white - similar to the image below.

I want the colors to exactly match the picture - a blend of normal pink, dark pink, and white.

The issue I'm facing is that my globe ends up displaying only a single color instead of the desired mix of colors as shown in the image. Any assistance or guidance would be greatly appreciated. Thank you in advance for all your help!

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / 
window.innerHeight, 1, 1000);

camera.position.z = 10;
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
antialias: true
});

renderer.setClearColor(0x2675AD);

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

var globe = document.getElementById('globe')

globe.appendChild(renderer.domElement);

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

var geom = new THREE.SphereBufferGeometry(5, 320, 160);
var colors = [];
var color = new THREE.Color();

var q = 0xC83C84;

for (let i = 0; i < geom.attributes.position.count; i++) {

color.set(Math.random() * q);

color.toArray(colors, i * 3);
}

geom.addAttribute('color', new THREE.BufferAttribute(new 
Float32Array(colors), 3));

var loader = new THREE.TextureLoader();
loader.setCrossOrigin('');
var texture = loader.load('../img/equirectangle_projection.png');
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(1, 1);
var disk = loader.load('../img/circleround.png');

var points = new THREE.Points(geom, new THREE.ShaderMaterial({
vertexColors: THREE.VertexColors,
uniforms: {
visibility: {
  value: texture
},
shift: {
  value: 0
},
shape: {
  value: disk
},
size: {
  value: 0.125
},
scale: {
  value: window.innerHeight / 2
}
},
  vertexShader: `

  uniform float scale;
  uniform float size;

  varying vec2 vUv;
  varying vec3 vColor;

  void main() {

    vUv = uv;
    vColor = color;
    vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
    gl_PointSize = size * ( scale / length( mvPosition.xyz ) );
    gl_Position = projectionMatrix * mvPosition;

    }
    `,
  fragmentShader: `
  uniform sampler2D visibility;
  uniform float shift;
  uniform sampler2D shape;

  varying vec2 vUv;
  varying vec3 vColor;


  void main() {

    vec2 uv = vUv;
    uv.x += shift;
    vec4 v = texture2D(visibility, uv);
    if (length(v.rgb) > 1.0) discard;

    gl_FragColor = vec4( vColor, 1.0 );
    vec4 shapeData = texture2D( shape, gl_PointCoord );
    if (shapeData.a < 0.5) discard;
    gl_FragColor = gl_FragColor * shapeData;

    }
   `,
    transparent: true
    }));
    scene.add(points);

    var blackGlobe = new THREE.Mesh(geom, new 
    THREE.MeshBasicMaterial({
     color: 0x2675AD
     }));
     blackGlobe.scale.setScalar(0.99);
     points.add(blackGlobe);

     var clock = new THREE.Clock();
     var time = 0;

     render();

     function render() {
     requestAnimationFrame(render);
     time += clock.getDelta();

     points.rotation.y  += 0.0009

     renderer.render(scene, camera);

}

Answer №1

You have the option to utilize an array of color values and select those values randomly:

var q = ["white", "pink", 0xb2497d, "gray"];
for (let i = 0; i < geom.attributes.position.count; i++) {
  color.set(q[THREE.Math.randInt(0,3)]);
  color.toArray(colors, i * 3);
}

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(1.25, 7, 7);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setClearColor(0x080808);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

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

var geom = new THREE.SphereBufferGeometry(5, 120, 60);
var colors = [];
var color = new THREE.Color();
var q = ["white", "pink", 0xb2497d, "gray"];
for (let i = 0; i < geom.attributes.position.count; i++) {
  color.set(q[THREE.Math.randInt(0,3)]);
  color.toArray(colors, i * 3);
}
geom.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));

var loader = new THREE.TextureLoader();
loader.setCrossOrigin('');
var texture = loader.load('http://learningthreejs.com/data/2013-09-16-how-to-make-the-earth-in-webgl/demo/bower_components/threex.planets/images/earthspec1k.jpg');
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(1, 1);
var disk = loader.load('https://threejs.org/examples/textures/sprites/circle.png');

var points = new THREE.Points(geom, new THREE.ShaderMaterial({
  vertexColors: THREE.VertexColors,
  uniforms: {
    visibility: {
      value: texture
    },
    shift: {
      value: 0
    },
    shape: {
      value: disk
    },
    size: {
      value: 0.125
    },
    scale: {
      value: window.innerHeight / 2
    }
  },
  vertexShader: `
  
      uniform float scale;
      uniform float size;
      
      varying vec2 vUv;
      varying vec3 vColor;
      
      void main() {
      
        vUv = uv;
        vColor = color;
        vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
        gl_PointSize = size * ( scale / length( mvPosition.xyz ) );
        gl_Position = projectionMatrix * mvPosition;

      }
  `,
  fragmentShader: `
      uniform sampler2D visibility;
      uniform float shift;
      uniform sampler2D shape;
      
      varying vec2 vUv;
      varying vec3 vColor;
      

      void main() {
      
        vec2 uv = vUv;
        uv.x += shift;
        vec4 v = texture2D(visibility, uv);
        if (length(v.rgb) > 1.0) discard;

        gl_FragColor = vec4( vColor, 1.0 );
        vec4 shapeData = texture2D( shape, gl_PointCoord );
        if (shapeData.a < 0.5) discard;
        gl_FragColor = gl_FragColor * shapeData;

      }
  `,
  transparent: true
}));
scene.add(points);

var blackGlobe = new THREE.Mesh(geom, new THREE.MeshBasicMaterial({
  color: 0x000000
}));
blackGlobe.scale.setScalar(0.99);
points.add(blackGlobe);

var clock = new THREE.Clock();
var time = 0;

render();

function render() {
  requestAnimationFrame(render);
  time += clock.getDelta();
  points.material.uniforms.shift.value = time * 0.1;
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/91/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

How do you display a nested object in React after merging it?

To display the JSON below as an image, click https://i.stack.imgur.com/tixu4.png let finalSplit = [ { start: "73", end: "76", splits: [ { word: "Now", start: "73", ...

Create a visual representation of an item within a framework using an Angular directive

I am interested in using a directive to draw a triangle above a series of div elements. In my scenario, I have four squares and two values: charge and normal. The value of charge determines the color of the squares, while normal is used for drawing the t ...

Implementing a function as the `data-*` attribute for an element in Angular 6

I have a question about my component.ts file: import { Component, OnInit, AfterViewInit, ElementRef, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; import { environment } from '../../../enviro ...

Tips for transferring data and events between named views within Vue Router

I have a layout structured like this: .------------------------+----------------. | Current Tab Title | Controls | +------------------------+----------------+ | Tab1 Tab2 [Tab3] | +---------------------------------------- ...

Techniques for incorporating a variable into the value field in JavaScript

let y = data[1]; cell1.innerHTML ='<input id="text" type="text" value= "'y'"/>' ; This snippet of code does not render any content when attempting to pass the variable, but if you provide a specific value like "h", it will displa ...

Utilizing Mongoose Schema Enums Alongside TypeScript Enums

In our Typescript-based NodeJs project utilizing Mongoose, we are seeking the right approach to define an enum field on a Mongoose schema that aligns with a Typescript enum. To illustrate, consider the following enum: enum StatusType { Approved = 1, ...

Angular HTTP client implementation with retry logic using alternative access token

Dealing with access tokens and refresh tokens for multiple APIs can be tricky. The challenge arises when an access token expires and needs to be updated without disrupting the functionality of the application. The current solution involves manually updati ...

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

Ways to handle <select> change events effectively in materialize css

My attempt at using a basic jquery change listener on a materialize css select dropdown has been unsuccessful. $("#somedropdown").change(function() { alert("Element Changed"); }); 1) Can anyone provide guidance on how to add a listener to ...

Freemarker substitute & and &ampersand;

I am facing an issue with Freemarker. I need to eliminate all the special characters from this sentence as well as from similar sentences in the future: BLA BLA RANDOM &, RANDOM BLA In particular, I want to remove the & character. The platform ...

MUI: Issue with pseudo element appearing cropped outside of Paper container

I am facing an issue where a red arrow pseudo element '::before' is partially cut off outside its container '.MuiPaper-root'. I need the arrow to remain visible, any suggestions on how to fix this? Here is the relevant code snippet and ...

Tips for determining the height of the entire webpage using jQuery

I attempted the following code: $(window).height(); $("#content").height(); However, it did not provide an accurate value. ...

What guidelines should be followed for utilizing jQuery's Ajax convenience methods and effectively managing errors?

Imagine a scenario where I am trying to mimic Gmail's interface using jQuery Ajax to incorporate periodic auto-saving and sending functionalities. Error handling is crucial, especially in cases of network errors or other issues. Instead of just being ...

Problem with camera rotation while loading 3D objects in three.js at the beginning

Looking to rotate the camera when loading objects in Three.js. Can anyone provide guidance on the best approach for this? Would using a Perspective Camera be a good option? For some inspiration, check out ...

Issue when Updating Component State: React child cannot be an object

I'm currently in the process of familiarizing myself with React and how to manage component state. My goal is to build a component, set up the initial state using a constructor, make a GET request to the server to fetch an array of objects, and then ...

Image Handpicked by JCrop User

Successfully implemented JCrop example code for selecting an area on an image with a preview and getting coordinates. However, the challenge lies in allowing users to select an image from their file system, display it in the browser, and perform the afore ...

Using jQuery to restrict the occurrence of Ajax POST requests to once every 10 seconds

I created an interactive wizard using HTML that displays multiple panels. Users can navigate through the panels using a Next button and there is also a Finish button available. Whenever the user clicks on the next button, I have set up a click handler to s ...

Align pictures in the middle of two divisions within a segment

This is the current code: HTML: <section class="sponsorSection"> <div class="sponsorImageRow"> <div class="sponsorImageColumn"> <img src="img/kvadrat_logo.png" class="sponsorpicture1"/> </div& ...

I have come across this building error, what do you think is the cause of it?

My attempt to launch my company's React.js project, downloaded from Tortoise SVN, is encountering an issue. PS C:\Projects\Old EHR> yarn start yarn run v1.22.19 $ next start ready - started server on 0.0.0.0:3000, url: http://localhost:30 ...

Adding a delay to your JQuery wiggle effect

Is there a way to achieve an effect similar to the JQuery wiggle plugin? Check out this demo: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js" type="text/javascript"></script> <script src="http://static.manpoints.u ...