Maximizing the performance of shader color calls

Exploring shaders with Three.js is a new challenge for me, and I'm struggling to modify some crucial code without just adjusting the RGBA values. One limitation I face is being unable to enclose it within an .html() method. My goal is to apply 10 different shader colors.

varying vec3 vNormal;
void main() {
  float intensity = pow(0.4 - dot(vNormal, vec3(0.0, 0.0, 1.0)), 4.0);
  gl_FragColor = vec4(0, 0, 255, 1.0) * intensity; }
  //gl_FragColor = vec4(0, 0, 255, 1.0) represents the RGBA value
}

Currently, I'm stuck not being able to make any changes to that line of code besides leaving it as is for it to function properly. The only option I have is duplicating the ID in its script tag, adjusting the RGBA values, and assigning it to different <script> elements. However, repeating this process ten times is not ideal for efficiency.

You can access the complete necessary code through this fiddle. How would you go about altering the code so you can easily reference a shader color?

Answer №1

If you want to add a uniform for the color, check out this link to see an example of how it can be done with Three.js shaders.
Essentially, the HTML/shaders code looks like this:

<script id="vertexShader" type="x-shader/x-vertex">
void main() {
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
</script>

<script id="fragmentShader" type="x-shader/x-fragment">
uniform vec3 diffuse;
void main() {
  gl_FragColor = vec4(diffuse.x, diffuse.y, diffuse.z, 1.0);
}
</script>

To create the shader in JavaScript:

var uniforms = {
  diffuse: { type: "c", value: new THREE.Color(0xeeeeee) }
};
var vertexShader = document.getElementById('vertexShader').text;
var fragmentShader = document.getElementById('fragmentShader').text;
material = new THREE.ShaderMaterial({
  uniforms: uniforms,
  vertexShader: vertexShader,
  fragmentShader: fragmentShader,
});

You can change the color by modifying `uniforms.diffuse.value`. My example doesn't include vNormal and intensity, but you should get the concept.
The shaders could also be defined as JavaScript variables or Strings instead of directly in HTML.

Take a look at this version of your fiddle for reference.

For more experiments with Three.js shaders and ShaderMaterial, visit THIS page of mine.

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 to Use Jquery to Delete a Specific String

I've been attempting to remove certain strings from a string using Jquery, however it seems like the code isn't working and my variable remains unchanged. var classes = $("body").attr('class'); alert('.side-nav' + classes); c ...

I am interested in extracting specific data from the JSON response

I am trying to extract the value of the message parameter under the messages array where the parameter name is equal to documentId (highlighted in bold below). However, the code I have tried so far does not achieve this as needed. dynamic obj = JsonConver ...

Angular's Components and Directives: A Comprehensive Guide

My goal is to render a subview within a template and define the state inside the subview's controller when an element is clicked. I am separating it from the main controller because there will be further subviews within this initial subview. However, ...

Hovering triggers the appearance of Particle JS

I am attempting to add particle js as the background for my website. I have tried implementing this code snippet: https://codepen.io/nikspatel/pen/aJGqpv My CSS includes: position: fixed; z-index: -10; in order to keep the particles fixed on the screen e ...

What is the best way to link the :style attribute with object syntax and incorporate multiple background images?

I'm experiencing an issue trying to bind CSS style with the object syntax to an image. The style object includes the CSS property background which refers to multiple background images, but unfortunately, these images are not showing up. Template < ...

"Concealing Querystrings in Node.js and AJAX: A Step-by-Step

I want to create a simple login form using the ajax Post method. However, I am having issues with the querystring still appearing in the URL. Can anyone help me resolve this issue? Thank you for any assistance! [ https://i.stack.imgur.com/R76O4.png http ...

Discover the step-by-step guide to creating a dynamic and adaptable gallery layout using

I have encountered an issue with my gallery where the images stack once the window is resized. Is there a way to ensure that the layout remains consistent across all screen sizes? <div class="container"> <div class="gallery"> &l ...

Encountering an unexpected error: receiving a void element tag as input in React

Any ideas on how to resolve the following error message: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML` Check out my code snippet below: import "./styles.css"; export default function App() { re ...

Retrieve the downloaded status of a blob within a specific function

I need a way to verify if the blob downloading process is finished when generating an excel file on the NodeJS server side in response to a request from the React frontend side. Is there a method or promise that can help me achieve this? I want to update t ...

Error message in Node.js: Unable to establish connection to 127.0.0.1 on port 21 due to E

I am currently developing a simple application using node js, and I have encountered the following issue: Error: connect ECONNREFUSED 127.0.0.1:21 at Object exports._errnoException (util.js:1034:11) at exports _exceptionWithHostPort (util.js:1057: ...

Promise not being properly returned by io.emit

io.emit('runPython', FutureValue().then(function(value) { console.log(value); //returns 15692 return value; // socket sends: 42["runPython",{}] })); Despite seeing the value 15692 in the console, I am encountering an issue where the promise ...

Reduce the file size of CSS and JS files for Magento

We are facing an issue with minifying CSS and Javascript for our Magento website. Currently, the size of our website is 1.1 MB and we aim to reduce it to 1 MB or even lower if possible. I tried using the "CSS Settings" and "Javascript Settings" functions ...

Creating a dynamically changing AppBar component in material-ui-next React that responds to scroll events

Following the Material Design guidelines, the top app bar should exhibit specific behavior: When scrolling, the top app bar can [...] undergo the following changes: - Scrolling upwards hides the top app bar - Scrolling downwards reveals the top ...

The property 'clone' is undefined and cannot be read

Currently, I am using Fullcalendar to update events. My goal is to execute an ajax callback to retrieve the edited version of a specific event. The endpoint for this request should be at /controls/:id/edit. To achieve this functionality, I have implemented ...

Issue with the System.Web.HttpRequestValidationException

I've been grappling with an issue related to a week-long problem that involves the error message System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client. This issue arises specifically when de ...

Is it possible to send requests to multiple APIs using a TypeScript event handler?

I'm facing a challenge in pinging multiple APIs within a single function. It seems like it should be possible, especially since each API shares the same headers and observable. I attempted to write a function for this purpose, but unfortunately, it do ...

What causes parseInt to transform a value into infinity?

Here is what I'm working on: let s = '50'; let a = parseInt(s); console.log(a); //outputs 50 console.log(_.isFinite(a)); //outputs false I'm curious why parseInt turns 'a' into infinity when 'a' is set to 50? ...

Please refrain from displaying the POST response in Express

I have a simple Express API setup: app.get('/example', function(req, res) { if (req.body.messageid == 1) { res.send({message: "Message"}); } } The API returns a message to be displayed on an HTML page. To display the message, I created ...

Tips for creating boxes with clearly defined edges on shared sides using three.js

When I draw boxes with common sides, I don't see the common edges, but rather perceive them as a single object even though there are 25 boxes: https://i.sstatic.net/gE8FW.png function box(scene, x, y, z, size) { const points = []; ...

The script is not functioning properly due to an error stating "(Uncaught ReferenceError: $ajaxUtils is not defined)"

I'm having trouble figuring out what the issue is (Uncaught ReferenceError: $ajaxUtils is not defined) document.addEventListener("DOMContentLoaded", function (event) { showLoading("#main-content"); $ajaxUtils.sendGetReque ...