Options for line colors in three.js

Here is the code I currently have:

  const materialLinearInterpolation = new THREE.LineBasicMaterial({ color: 0x0000c9, linewidth: 1 })
  const pointsLinearInterpolation = []
  for (var i = 0; i < this.pointsCoordinatesLinearInterpolation.length; i++) {
    pointsLinearInterpolation.push(
      new THREE.Vector3(
        this.pointsCoordinatesLinearInterpolation[i].x,
        this.pointsCoordinatesLinearInterpolation[i].y,
        this.pointsCoordinatesLinearInterpolation[i].z
      )
    )
  }
  const geometryLinearInterpolation = new THREE.BufferGeometry().setFromPoints(pointsLinearInterpolation)
  this.lineLinearInterpolation = new THREE.Line(geometryLinearInterpolation, materialLinearInterpolation)

  this.scene.add(this.lineLinearInterpolation)

I am looking for a way to use different colors for multiple lines in this setup. If this is not possible, I would like to know how to draw several connected lines with different colors.

Answer №1

To achieve a unique color for each line segment, it is necessary to utilize THREE.LineSegment along with vertex colors, as demonstrated in the live example below:

let camera, scene, renderer;

init();
render();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.z = 3;

  scene = new THREE.Scene();

  const geometry = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, 0), new THREE.Vector3(-1, 0, 0)]);

  const colors = [
    255, 255, 0, 255, 255, 0,
    0, 255, 255, 0, 255, 255
  ];

  geometry.setAttribute('color', new THREE.Uint8BufferAttribute(colors, 3, true));

  const material = new THREE.LineBasicMaterial({
    vertexColors: true
  });

  const lines = new THREE.LineSegments(geometry, material);
  scene.add(lines);

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

}

function render() {

  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="c8bca0baadad88f8e6f9fbf8e6f9">[email protected]</a>/build/three.min.js"></script>

Using THREE.Line instead could result in a color gradient between line segments, which may not always be desirable.

Answer №2

Unique solution using WebGL2.0, implementing flat for the vColor varying by adjusting the shaders within the onBeforeCompile method:

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth/innerHeight, 1, 100);
camera.position.set(0, 0, 10);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

let grid = new THREE.GridHelper(10, 10, 0x7f7f7f, 0x444444);
grid.rotation.x = - Math.PI * 0.5;
scene.add(grid);

const vertCount = 11;
let c = [];
let g = new THREE.BufferGeometry().setFromPoints(new Array(vertCount).fill(0).map((p,idx) => {
  c.push(idx / (vertCount - 1), idx % 2, idx % 3);
  return new THREE.Vector3(((vertCount - 1) * -0.5) + idx, (Math.random() - 0.5) * 10, 0); 
}))
g.setAttribute("color", new THREE.Float32BufferAttribute(c, 3));

let m = new THREE.LineBasicMaterial({
  vertexColors: true,
  onBeforeCompile: shader => {
    shader.vertexShader = shader.vertexShader.replace(
      `#include <color_pars_vertex>`,
      `flat out vec3 vColor;`
    );
    console.log(shader.vertexShader);
    shader.fragmentShader = shader.fragmentShader.replace(
      `#include <color_pars_fragment>`,
      `flat in vec3 vColor;`
    );
    console.log(shader.fragmentShader);
  }
});
let l = new THREE.Line(g, m);
scene.add(l);

renderer.setAnimationLoop( _ => {
  renderer.render(scene, camera);
})
body{
  overflow: hidden;
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f6829e849393b6c6d8c7c5c6d8c7">[email protected]</a>/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

Error message: The function client.on is not defined as a valid function

const Discord = require("discord.js"); const client = new Discord.Client(); module.exports = { name: "voiceStateUpdate", run: async (message, client) => { client.on("voiceStateUpdate", (o ...

drag and zoom feature similar to Google Maps

Is it possible to create draggable effects similar to Google Maps on a group of div elements? Are there any JavaScript libraries available that can replicate this functionality? ...

What is the best way to include a text input as the last option in a Select input form field?

I would like to implement a select input feature where users can choose from predefined options, with the added functionality of including a text input field as the last option for users who prefer to enter their own category. How can I achieve this? Curr ...

Ensure the initial value in the dropdown menu is automatically set to the first value in VueJs

How can I set the first value of my time object as the default value for my dropdown in Vue? I want the first value to be pre-selected when a user enters the website, but currently only display the value without actually selecting it. time Object:- { &quo ...

What makes running the 'rimraf dist' command in a build script essential?

Why would the "rimraf dist" command be used in the build script of a package.json file? "scripts": { "build": "rimraf dist ..." }, ...

Is it possible to use Ajax to prompt a pop-up window for basic authentication when logging in?

While attempting to access the reed.co.uk REST web API in order to retrieve all related jobs, I am encountering an issue. Despite passing my username and password, a popup window keeps appearing when I call the URL. The alert message displayed reads: i ...

Navigating through cards in HTML: A guide to filtering techniques

I'm currently in the process of developing a platform that enables users to browse through different profiles based on their first names. I've attempted to utilize bootstrap's "data-title" for searching purposes, but unfortunately, it's ...

JSON failing to show all values sent as a string

In a div element there is a table with 3 rows, a textarea, and a button. The JSON data populates the first 3 rows correctly but the textarea remains blank. My goal is to display the previous record from the database in the textarea. function ChangeLoadin ...

Tips on capturing a URL using JQuery

Currently, I am in the process of importing an external HTML file into my webpage. Within this file, there is a JavaScript method linked to a form submission event. function ValidateInput(){ //some code if(validationFailed){ ...

What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js? I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone el ...

Utilizing Json data with Jquery for dynamically placing markers on Google Maps

Seeking assistance as I am currently facing a problem where I need to loop through JSON data and add it as markers on Google Maps, but unfortunately, it only returns null value. Is there a way to automatically connect this to JSON? My plan is to have a Gr ...

In the process of making a request with axios in an express server

Struggling with a simple call to an API using Axios with Express, and I can't figure out why it's always pending in the browser. Here is my route: var express = require("express"); var router = express.Router(); const controller = require("../. ...

$scope.apply is triggering both "catch" and "then" handlers

I am trying to ensure that the content of a page in Angular 1.6.2 and UI router is only displayed once it has been confirmed on the server that the user has the appropriate role/permissions. It seems like without using $scope.apply(), the catch() function ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...

Issue with implementing bootbox and jQuery.validator for AJAX login form collaboration

Here's a fiddle link that showcases the issue I'm facing. The problem arises when I try to Sign In on an empty modal form. The validator should highlight any fields in error and proceed to submit the form once the validation is successful. I&ap ...

Submitting form based on HTML select input issue

I am facing an issue with a select form where the value resets to "10" every time I send the form. Is there a way to keep the selected option, for example "20", after submitting the form? Below is the code snippet: <form method='get' name=&a ...

What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...

ReactJS encountered an error: [function] is not defined, July 2017

Attempting to convert a JSON file into an array and then randomly selecting 5 items from it. I suspect the issue lies in my render/return statement at the end of ImageContainer.js, but as a newbie in ReactJS, it could be anything. Any assistance or guida ...

The XML data is valid, however the responseXML property in the XMLHttpRequest response is null

Click here to access the API URL, which returns XML data. However, the responseXML property in the XMLHttpRequest response is coming back empty. How can I retrieve the XML data from the response? document.body.onload = loadXMLDoc(); function loadXMLDoc ...

Unable to retrieve JSON data from the remote URL

I have been attempting to retrieve information from but unfortunately, I am not receiving any data in return. Despite this, I can see the data in my response tab using Google Chrome. My attempts include running it on both a webserver and locally for test ...