Can you provide guidance on achieving a gradient effect throughout the mesh, similar to the one shown in the example?

Check out my code snippet on JSFiddle: https://jsfiddle.net/gentleman_goat66/o5wn3bpf/215/

https://i.sstatic.net/r8Vxh.png

I'm trying to achieve the appearance of the red/green box with the border style of the purple box. The purple box was created using BoxGeometry, while the red/green one was manually generated with vertices and passed to BufferGeometry.

The goal is to retain the borders of the pink box in this JSFiddle, but incorporate the red/green gradient effect.

I've developed a custom shader that outlines the geometry with a black border by leveraging UV edges. However, I'm struggling to implement the red to yellow to green gradient effect achievable with MeshStandardMaterial

As seen in the code, I managed to create a partial gradient using vUv.y, but the alignment on the top face isn't correct. How can I modify the UVs and Shadercode to produce this effect within my existing custom shader?

In simpler terms, refer to an alternate JSFiddle: (https://jsfiddle.net/gentleman_goat66/o5wn3bpf/216/)

The objective is for the pink box in this JSFiddle to maintain its borders while exhibiting the red/green gradient effect.

https://i.sstatic.net/ScjJd.png

https://i.sstatic.net/Rk3uo.png

HTML

<script type="importmap">
{
"imports": 
  {
    "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f08498829595b0c0dec1c5c1dec3">[email protected]</a>/build/three.module.js",
    "OrbitControls": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e3978b918686a3d3cdd2d6d2cdd0">[email protected]</a>/examples/jsm/controls/OrbitControls.js"
  }
}
</script>
...

JS

import * as THREE from 'three';
import { OrbitControls } from 'OrbitControls';

class Heatmap {
  constructor(){
    console.log("Heatmap - constructor()");
    
    //ThreeJS Variables
    ...
}

$(document).ready(function(){
  console.log("DOM ready!");
  new Heatmap();
});

CSS

body,html{
  margin: 0;
  width: 100%;
  height: 100%;
}
#container {
  width: 100%;
  height: 100%;
  background-color: black;
  margin: 0;
}

UPDATE:

Here's an example demonstrating the desired color effect with boxGeometry: https://jsfiddle.net/gentleman_goat66/o5wn3bpf/249/

Now I just need to implement that functionality within the shader.

Answer №1

I managed to resolve the issue by ensuring that the color vector information is correctly passed and the shader effectively interacts with the attribute color.

You can find my solution on JSFiddle: https://jsfiddle.net/gentleman_goat66/o5wn3bpf/249/

<script type="importmap">
{
"imports": 
  {
    "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e3a263c2b2b0e7e607f7b7f607d">[email protected]</a>/build/three.module.js",
    "OrbitControls": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e4908c968181a4d4cad5d1d5cad7">[email protected]</a>/examples/jsm/controls/OrbitControls.js"
  }
}
</script>
<script id="vertexShader" type="x-shader/x-vertex">

            #include <common>
      #include <uv_pars_vertex>
      #include <displacementmap_pars_vertex>
      #include <color_pars_vertex>
      #include <fog_pars_vertex>
      #include <morphtarget_pars_vertex>
      #include <skinning_pars_vertex>
      #include <shadowmap_pars_vertex>
      #include <specularmap_pars_fragment>
      #include <logdepthbuf_pars_vertex>
      #include <clipping_planes_pars_vertex>
      
            varying vec2 vUv;
      attribute vec3 color;
      varying vec3 vColor;
      
            void main() {
            
                #include <beginnormal_vertex>
                #include <morphnormal_vertex>
                #include <begin_vertex>
                #include <morphtarget_vertex>
                
        vUv = uv;
        vColor = color;
        
                //gl_Position = vec4( transformed, 1.0 );
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);

            }

</script>
<script id="fragmentShader" type="x-shader/x-fragment">
            varying vec2 vUv;
      varying vec3 vColor;
      
        uniform float thickness;
      
      float edgeFactor(vec2 p){
        vec2 grid = abs(fract(p - 0.5) - 0.5) / fwidth(p) / thickness;
        return min(grid.x, grid.y);
        }
      
            void main() {

                float a = edgeFactor(vUv);
      
        vec3 c = mix(vec3(0), vec3(0.1), a);
        if(a >= 1.0){
            c = vec3(vColor.r,vColor.g,vColor.b);
        }
      
        gl_FragColor = vec4(c, 1.0);

            }

</script>
<div id="container">
</div>

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

What is the best way to thoroughly uninstall Ionic and Cordova from an Ubuntu system?

Is there a way to completely remove Cordova and Ionic 1 and all of their dependencies from my Ubuntu system? And how can I reinstall them again? I found this blog helpful for installing Ionic and its dependencies: I attempted to uninstall Cordova and Ion ...

Creating enduring designs in Next.js

I've been diving into this amazing article and I'm puzzling over the implementation of persistence in Option 4. It seems like you would need to redefine the .getLayout method for each page. I'm uncertain about how nesting logic is handled fo ...

Exploring the interaction between nested view controllers and ng-click in AngularJS

There are 8 different jade views, but only one is loaded and filled with jquery into a div that has a controller. I have two questions: Do I need to define the controller again on top of my partial view (the same controller as the main one)? All views h ...

Having trouble loading script files with JSDOM in NodeJS?

I'm currently experimenting with loading an HTML page in jsdom to generate graphs, but I'm facing challenges in getting the JavaScript to execute. Here's the HTML page I'm trying to load, which simply renders a basic graph: <html&g ...

Discovering the nearest sibling using jQuery

My HTML code snippet is as follows: $(".remove-post").click((event) => { $(event.target).fadeOut(); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="side-bar"> <b ...

Tips for selecting a checkbox with Puppeteer

I've implemented the code in this way: await page.$eval('input[name=name_check]', check => { check.checked = true; }); This code is intended for multiple checkboxes. However, I need it to work for a single checkbox only. Is there a way ...

Understanding the distinction between deleting and nullifying in JavaScript

var obj = {type: "beetle", price : "xxx", popular: "yes" ,.... }; If I want to remove all the properties from obj, what is the correct way to do it? Should I use delete obj.type; delete obj.price; delete obj.popular ... and so on. Or should I set ob ...

Ways to prevent styles from being overridden by those specified in JavaScript

Some elements on my page have their style dynamically changed by JavaScript. However, I want one of them to maintain its static style without being overridden. Is there a way to specify that the style of this particular element should not be altered? Than ...

Shaded by its own bump map sprite, casting intricate shadows

My implementation of normal map lighting for 2D sprites in webgl (GLSL shaders) is fairly straightforward and has been adapted and optimized from an example. It utilizes a single directional light and serves its purpose well. The sprites are displayed flat ...

Switch the div class when clicked, and revert it when the body is clicked

Allow me to elaborate on the issue: I currently have <div class="contact"> <div id="form"></div> <div id="icon"></div> </div> My goal is to change the class of .contact to .contactexpand (or simply ...

Tips for retrieving the 'Created' value in vue.js

I am currently trying to fetch API JSON data for a weather widget, but unfortunately it is returning null. While I am able to retrieve the JSON data successfully, I am struggling to handle this value. Below is my HTML code snippet: <html> <head& ...

What's the reason behind the console showing an uncaught promise error message?

When attempting to delete some lists from my backend using a fetch request, I encountered an issue. The console is displaying an error message that reads "Uncaught (in promise)." What could be causing this problem? Here is the frontend code snippet for th ...

What is the designated action or code in question?

let specialty = ''; function isVegetarian() { }; function isLowSodium() { }; export { specialty, isVegetarian }; export { specialty, isVegetarian }; The explanation from the editor was as follows: When exporting objects, it is done by the ...

Switching the children image source by hovering over the parent element

I have a React component that functions as a card containing a title and an image. I want the image to change upon hovering over the entire card, rather than just the img element itself. While CSS and the background property could achieve this, I prefer k ...

Using jQuery to access a server-side SQL database through PHP

After searching for an example on connecting a client to a server's SQL database using JQuery, AJAX, and PHP, I came across this seemingly well-executed guide: Example Link. All my PHP files and the jQuery library (javascript-1.10.2.min.js) are contai ...

Why won't the code for detecting the DEL key in a textarea work on my computer?

I've been trying to detect when a user presses the Delete key and came across this helpful tutorial here The code worked flawlessly on jsfiddle.net, you can check it out here- http://jsfiddle.net. However, when I copied the same code to my local comp ...

What could be causing me to receive 'undefined' and an empty array[] when using Promise.all with JavaScript async operations making calls to Azure APIs?

In my personal project utilizing Azure AI APIs and Node.js/Express,, I am working on handling a get request to a /viewText route by extracting text and key phrases from an uploaded image/document. Below is the code snippet that should log this data to the ...

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

change the return value to NaN instead of a number

Hey there, I have something similar to this: var abc1 = 1846; var abc2 = 1649; var abc3 = 174; var abc4 = 27; if(message.toLowerCase() == ('!xyz')) { client.say(channel, `abc1` +`(${+ abc1.toLocaleString()})` +` | abc2 `+`(${+ abc2.toLocaleStri ...

Displaying a dynamic flag icon in a span element based on the selection from a mat-select

I am working on a mat-select component and I want to dynamically change a flag icon inside a span element in the mat-label based on the selected option. Currently, the initial flag is displayed correctly, but when I click on a different option, the flag d ...