Using Three JS Circle Line Geometry to Color Negative Values

I've been experimenting with different methods to change the color of a circle based on positive and negative Z values. One approach I tried involved creating two separate line segments with different materials, but I encountered issues when the segments crossed the Z=0 boundary, resulting in gaps. Is it possible to achieve this effect using just one line Geom and changing the color of the section that falls into negative Z values? I'm uncertain about the best approach to take. Thank you for any guidance!

Here's a snippet of my current test (using X,Y):

<html>
    <head>
        <title>Circle Color</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
    </head>
    <body>
    <script src="three.min.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 500, window.innerWidth/window.innerHeight, 0.1, 100000 );

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

                var segmentCount = 100,
                    radius = 10,
                    geometry = new THREE.Geometry();
                    geometry2 = new THREE.Geometry();
                    material = new THREE.LineBasicMaterial({ color: "#5fd119" }); // light green
                    material2 = new THREE.LineBasicMaterial({ color: "#3d8710" }); // darker green

                    //PUSH THE ORIGIN VERTICY IN
                    geometry2.vertices.push(new THREE.Vector3(-10,0,0));

                for (var i = 0; i <= segmentCount; i++) {
                    var theta = (i / segmentCount) * Math.PI * 2;

                    x = Math.cos(theta) * radius;
                    y = Math.sin(theta) * radius;
                    z = 0;

                    if (y >=0 ){
                        geometry.vertices.push(new THREE.Vector3(x, y, z));  
                    } else {
                        geometry2.vertices.push(new THREE.Vector3(x, y, z));
                    }          
                }

                scene.add(new THREE.Line(geometry, material));
                scene.add(new THREE.Line(geometry2, material2));

            camera.position.z = 5;

            var render = function () {
                requestAnimationFrame( render );

                renderer.render(scene, camera);
            };

            render();
        </script>
    </body>
</html>

After implementing the suggested solution below, everything is functioning smoothly: https://i.sstatic.net/1OBpm.png

Answer №1

It's important to understand how you can customize the colors of vertices in a geometry. By setting the colors of the vertices and then utilizing the vertexColors parameter of a material, you can achieve the desired effect.

  var radius = 5;
  var shape = new THREE.Shape();
  shape.moveTo(radius, 0);
  shape.absarc(0, 0, radius, 0, 2 * Math.PI, false);
  var spacedPoints = shape.createSpacedPointsGeometry(360);

  var vertexColors = []; // array for storing vertex colors
  spacedPoints.vertices.forEach( function( vertex ){ // populate the array
    if( vertex.y < 0 )
      vertexColors.push( new THREE.Color( 0xff0000 ))
    else
      vertexColors.push( new THREE.Color( 0x0000ff ));
  });
  spacedPoints.colors = vertexColors; // assign the array

  var orbit = new THREE.Line(spacedPoints, new THREE.LineBasicMaterial({
    vertexColors: THREE.VertexColors // set this parameter as shown here
  }));
  scene.add(orbit);

Check out this jsfiddle example

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

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

What could be causing the AngularUI bootstrap datepicker to not appear?

Exploring the popup datepicker demo from angularUI bootstrap, which is embedded in their page and works perfectly. However, when I tried to create a minimal plunker here, the button click does not open the calendar. Any thoughts on what might be causing th ...

Issue #98123 encountered during execution of `npm run develop` command, related to WEBPACK

I want to start a brand new Gatsby site following the instructions provided on . Here's what I did: npm init gatsby # see note below cd my-gatsby-site npm run develop Note: I didn't make any changes to the configuration, so I'm using JavaS ...

Transferring identification data between views within an application (AngularJS, NodeJs, HTML)

I'm working on an HTML page that lists users from MongoDB. The page allows for deleting and updating users. I am encountering an issue with the update button - I want a new HTML page to appear with a form when the button is clicked, capturing the user ...

Navigate your way with Google Maps integrated in Bootstrap tabs

Trying to display a Google Map in a vanilla Bootstrap tab has been quite the challenge. I created a fiddle based on the Bootstrap docs, and followed Google's instructions for the Gmap script. The map object appears initialized when checking console.di ...

:Incorporating active hyperlinks through javascript

Hey there, I've encountered a little conundrum. I have a header.php file that contains all the header information - navigation and logo. It's super convenient because I can include this file on all my pages where needed, making editing a breeze. ...

Algorithm for File Naming

Given an array of desired file names in the order of their creation, where two files cannot have the same name. If a file has a duplicate name, it will be appended with (k), where k is the smallest positive integer that creates a unique name. Output an ar ...

Steps to ensure a dropdown menu remains expanded when its nested menu is selected

Check out this dropdown list here, but the issue arises when clicking on a nested menu item such as "Books Registration". Once that page loads, the dropdown menu collapses like shown here. Here's a snippet of the dropdown code: <ul class="nav nav- ...

Exploring scroll functionality with Webdriver.io v4

My code is designed to log into the beta version of mediawiki, navigate to the Preferences page, and attempt to click on a button located at the bottom of the page. In order to achieve this, I am utilizing the scroll() function because using only .click() ...

Troubleshooting issues with Vue.js page routing

Currently, I am diving into the world of vue.js and encountering difficulties with setting up routing. My goal is to utilize templates stored in separate HTML files, rather than inline templates. The issue I'm facing is that the routing does not seem ...

Traveling within a layered object

Currently, I'm working with an object and iterating through it to retrieve outputs as shown below: var obj = { "first": { "Bob": { "1": "foo", "2": "bar" }, "Jim": { "1": "baz" } }, "second": { "Bob": { ...

Are you facing a CORS problem with Three.js black video?

Dealing with a persistent issue where black video with sound appears in a Three.js texture on both mobile and desktop devices has been quite a challenge for me. I've tried various solutions, but here's where I currently stand: if(!video || vide ...

How to retrieve the value of a SelectField component within a constant using Material-UI

I am currently facing an issue with my Drawer component that contains a SelectField with some fields. I am struggling to get the value and implement the onChange functionality of the Field. Below is the snippet of my code: const DrawerCargoAddItem = (p ...

Using the Trigger Method in a Vue JS Component with Sibling Components

Seeking assistance once again for a VueJS2 project. Currently, I have a setup with a parent component, along with child1 and child2. The scenario is that the form in child1 needs to receive data from child2, which acts as a table. When a checkbox on a row ...

Ensuring child input components are validated upon submission using Vee-Validate and Vue.js 2

Currently, I am working on creating a Registration form with multiple "Input Field" components that require validation once the Submit button is pressed. While each input field validates individually when the text is changed, I am struggling to implement a ...

Should you include the dollar sign in a Vue HTML variable or not?

I’m a bit confused about whether or not I should include $ when using a Vue HTML variable: new Vue({ data: { a: "myData" } }); Do I need to use: <h1>My value is {{ a }}</h1> or <h1>My value is {{ $a }}</h1> What ...

Retrieve data from an array within the user Collection using Meteor and React Native

I need assistance with retrieving the entire array [votes] stored within the User Collection. Below is the JSON structure { "_id" : "pziqjwGCd2QnNWJjX", "createdAt" : ISODate("2017-12-21T22:06:41.930Z"), "emails" : [ { "a ...

In Vue, props are not automatically assigned; be sure to avoid directly mutating a prop when assigning it manually to prevent errors

I am working with two Vue components: GetAnimal.vue and DisplayAnimal.vue. GetAnimal.vue sends a JSON object containing animal data to DisplayAnimal.vue using router push. DisplayAnimal.vue then displays this data. The process flow is as follows: I navigat ...

Utilizing Font Awesome icons within Chart.js labels

I can't seem to display font awesome symbols as labels in my chart.js 1. I have already added fontawesome's css file 2. I have selected the symbols from this link 3. I have updated the chart.js options to set pointLabels.fontFamily to FontAwes ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...