Change the color of the line segment connecting two points on a line

In my three.js project, I am working on drawing a line based on an array of vertices. One challenge I am facing is setting the color of the line to a specific value between two points along the line that are not actual vertices. These two points exist at a certain distance from the line's origin - for example, I want to change the color between 50 and 100 units along a line that is 500 units long. How can I achieve this?

Although using vertexColors: THREE.VertexColors allows me to specify colors between line vertices, it does not help in coloring between non-vertex points. It seems like I might need to add these two points as additional vertices, but then comes the question of how to determine their position with XYZ coordinates along the line.

If you have any suggestions or hints on how I could accomplish this, I would greatly appreciate your input!

Answer №1

To customize the THREE.LineDashedMaterial(), you can utilize the .onBeforeCompile() method:

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

scene.add(new THREE.GridHelper(500, 10));

var geom = new THREE.BufferGeometry().setFromPoints(
  [
    new THREE.Vector3(-250, 0, 0),
    new THREE.Vector3(250, 0, 0)
  ]
);

var mat = new THREE.LineDashedMaterial({
  color: "red"
});
var uniforms = {
  segmentStart: {
    value: 50
  },
  segmentEnd: {
    value: 100
  },
  segmentColor: {
    value: new THREE.Color("yellow")
  }
}
mat.onBeforeCompile = shader => {
  shader.uniforms.segmentStart = uniforms.segmentStart;
  shader.uniforms.segmentEnd = uniforms.segmentEnd;
  shader.uniforms.segmentColor = uniforms.segmentColor;
  shader.fragmentShader = `
    uniform float segmentStart;
    uniform float segmentEnd;
    uniform vec3 segmentColor;
  ` + shader.fragmentShader; // add uniforms
  shader.fragmentShader = shader.fragmentShader.replace(
    `if ( mod( vLineDistance, totalSize ) > dashSize ) {
discard;
}`, // remove the part for dash
    ``
  );
  shader.fragmentShader = shader.fragmentShader.replace(
    `gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,
    `gl_FragColor = vec4( outgoingLight, diffuseColor.a );
    if (vLineDistance >= segmentStart && vLineDistance <= segmentEnd) gl_FragColor.rgb = vec3(1, 1, 0);
    `
  ); // add showing of a segment


  console.log(shader.fragmentShader);

}

var line = new THREE.Line(geom, mat);
line.computeLineDistances();
scene.add(line);

var clock = new THREE.Clock();

renderer.setAnimationLoop(() => {

  uniforms.segmentEnd.value = 250 + Math.sin(clock.getElapsedTime()) * 150;
  renderer.render(scene, camera)
});
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.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

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...

Using NodeJS to retrieve the mean price from the OPSkins pricelist

Is there a way to calculate the average price of every skin listed in this document? I'm wondering how one would go about using the dates and prices in order to determine the 60-day average price. My approach would involve extracting the data from t ...

Upgrade to the latest Gulp version and transition away from using the gulp.start function

Currently in the process of updating all my gulp v3 projects to v4, but running into an issue with the gulp start function. Upon executing gulp start in gulp v4, I encounter an error. This was the code snippet I used in v3: gulp.parallel within gulp.seri ...

I attempted to retrieve a card using two nested maps, but unfortunately the data did not display as expected

I attempted to add data in Gotocart.jsx using a nested map, but I'm having trouble getting anything to display on the page. Below is the code for Gotocart.jsx: import React from 'react' import { useState } from 'react' import { da ...

Closing the Material UI Drawer

Having an issue with my material UI drawer - I can open it successfully, but when attempting to close it, the event does not trigger. import React from 'react'; import './App.css'; import { fade, makeStyles } from '@material-ui/co ...

Generate a circular shape wherever the mouse is moved

I'm currently working on implementing a custom mouse trail using temporary divs. These divs are supposed to appear at the location of the mouse and then fade out after a short period. However, I've run into an issue where the divs only appear at ...

Error: Attempting to access a property of an undefined value, please verify the key name is

Attempting to incorporate dynamic elements into the assignment, I have written the following code: var contentList = Object.keys(content)[0]; $scope.model.currentLoadedContent[contentList] = content[Object.keys(content)[0]] When trying to execute the seco ...

Stopping the timer with clearInterval isn't functioning as expected

I posted my work online here: Instructions on how to reproduce: Click on a green pin on the map to select a station Fill in the fields for name and last name Sign on the canvas A timer should start counting down from 20 minutes If you click on the ...

Use the selector on elements that have been previously chosen

Sorry if this is a silly question, but maybe today's just not my day. Say I already have a selected element, for example: let tables = $('table'); Now, what if I want to add another selector like .some-class to those tables, without creati ...

What is the best method for efficiently loading SVG icons on an HTML page without redundancy? / Is utilizing <use href> recommended?

My struggle with implementing icons in Angular While working on a new Angular project, I've encountered challenges with my current SVG-icon implementation method from a previous project (@ngneat/svg-icon). The process involves organizing SVG files in ...

A guide on harnessing the power of NPM modules

I have a simple question as someone who is new to frontend web development. After I use the command npm install to install something, how do I go about utilizing it? For instance, I recently executed npm install bootstrap, and now I want to apply the CSS ...

Assigning a value to a cell depending on a specific condition

Currently, I have a column connected to a field known as state. The possible values for this field are either S or L. My objective is to map these values as follows: S => Short, L => Long The binding is structured in the following way: $scope.grid ...

Is it possible to maintain the sidebar while eliminating the scrolling JavaScript?

Looking to recreate the image display style on Facebook where pictures appear in a lightbox format. The challenge I'm facing is figuring out how they manage to have the sidebar with no visible scroll bar inside... If you want to see this for yourself ...

Harmonizing Express (Passport) with AngularJS Routing

I have been working on developing a MEAN-stack application and I have reached the point of setting up user authentication. Following this tutorial: After implementing it into my project, I noticed that it works partially. The issue is that I can only acce ...

Configuring Angular 6+ Applications at Run Time

What is the most effective approach for loading environment-specific configuration at runtime in an Angular application? The Angular documentation suggests utilizing APP_INITIALIZER, but this may not be early enough in the loading process for configuring i ...

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

A guide to implementing daily function calls for a week utilizing the @nestjs/scheduler module

Is there a way to schedule a function to run every day for a period of 7 days using Nestjs (@nestjs/scheduler)? @Cron(new Date(Date.now() + (24*60*60*1000) * 7) function() { console.log("This should get called each day during the next 7 days") ...

Enhance your JavaScript skills by deserializing objects and seamlessly integrating new methods

Currently in my Javascript code, I am utilizing localStorage. Since objects cannot be directly stored in it, I am using JSON.stringify to serialize them before saving. Within localStorage, I am storing the entire game state, where some of the sub-objects ...

Seeking guidance on navigating a Bootstrap tabbed navigation menu with nested dropdowns using previous and next buttons

My template features tabbed navigation with a nested dropdown menu. The previous and next buttons are meant to provide secondary navigation through each of the tabs. The issue arises when trying to navigate through the pages in the dropdown menu using the ...

Is there a way to embed a JS media query inside the sticky navbar function for both the onscroll and onclick events?

I've been exploring media queries in JavaScript, and it seems like they work well when the window is resized. However, when nested within onscroll and onclick functions, things start to get a bit tricky. If you run the following code and resize the w ...