Shading THREE.js Color with Textures

I have added a simple box to my scene, and I am looking to create a shader that will apply a texture to it and add color to this texture.

Here is my vertex shader (nothing special about it):

<script id="vertexShader" type="x-shader/x-vertex">
        varying vec2 vUv;
        void main() {
        vUv = uv;

        gl_Position =   projectionMatrix * modelViewMatrix * vec4(position,1.0);
        }
</script>

And here is my fragment shader:

<script id="fragmentShader" type="x-shader/x-fragment">
        uniform vec2 resolution;
        uniform float time;
        uniform sampler2D texture;
        varying vec2 vUv;
        uniform vec3 color;
        varying vec3 vColor;
        void mainImage( out vec4 fragColor, in vec2 fragCoord )
        {
        vec2 uv = fragCoord.xy / vec2(1920.0, 1920.0);
        fragColor = vec4(uv, 0.5 + 0.5 * cos(time) * sin(time) ,1.0);
        }
        void main( void ) {
        vec4 color = vec4(0.0,0.0,0.0,1.0);
        mainImage( color, gl_FragCoord.xy );

        color.w = 1.0;
        gl_FragColor = texture2D(texture, vUv);
        gl_FragColor = color;

        }
 </script>

In the last two lines of code, I set gl_FragColor with texture and color. When the last line is gl_FragColor = color;, the result looks like: https://i.sstatic.net/6Wt1r.png However, when I change the order and the last line is

gl_FragColor = texture2D(texture, vUv);
, the result changes to: https://i.sstatic.net/2Evzu.png

This is the code used to apply the shader and add a box to the scene:

var geometry = new THREE.BoxGeometry(.5, 1, .5);    
uniforms = {
   time: { type: "f", value: 1.0 },
   resolution: { type: "v2", value: new THREE.Vector2() },
   texture: { type: "t", value: THREE.ImageUtils.loadTexture("../img/disc.png") }
            };

var material = new THREE.ShaderMaterial({
                transparent: true,
                uniforms: uniforms,
                vertexShader: document.getElementById('vertexShader').textContent,
                fragmentShader: document.getElementById('fragmentShader').textContent

            });

var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

Is there a way to achieve the same effect as shown in the pictures by coloring my texture (mixing color and texture in the object) using this shader?

Answer №1

When it comes to variables, setting them twice will simply overwrite the previous value with the latest one;

var bar;
bar = 789;
bar = 321;

Now, bar is equal to 321

If you wish to combine the values, you'll need to perform a manual combination:

 gl_Position = position + offset;
 gl_Position = new_position;

This means gl_Position ends up being new_position;

Perhaps what you're looking for is something like this:

 final_value = first_value * second_value;

However, the actual mathematical operation depends on your specific goal.

Based on the provided texture and color, multiplying the texture by the color results in a gradient circle. It's uncertain if that aligns with your intended outcome.

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

Is there a way to navigate to a newly created document?

Is there a way to automatically redirect a user to the show action of a document or post they have just created using express.js? Take a look at the following code snippet, which outlines how I am creating the document: app.post('/document/create&ap ...

Using Bootstrap to handle opening a link when a dropdown menu button is clicked

Utilizing Bootstrap in my main menu was essential for navigating through the numerous pages, subpages, and sub-subpages within my project. The dropdownmenu feature proved to be very helpful in this regard. However, my client now has a specific request - t ...

Repairing the Performance of the 'Save' Feature

Can the 'Save' button in my code save team assignments for players selected using drag and drop? I'm considering using localStorage, but unsure about implementation. Note: To run the code properly, copy it as an HTML file on your computer. ...

Maintaining hover effects even when elements are not in view

I am facing an issue with my absolutely positioned <div> (which serves as a menu) located in the corner of a webpage. The problem arises when I try to animate it on hover, but as soon as the cursor moves beyond the viewport, the hover action stops. I ...

Conditional return type mistakes

I'm facing an issue with a function that takes a parameter "value" and is supposed to return 0 or 1 based on its true or false value. Check it out here. const f = <T extends boolean>(value: T): false extends T ? 0 : 1 => { if (value === ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...

Leveraging symbols as object key type in TypeScript

I am attempting to create an object with a symbol as the key type, following MDN's guidance: A symbol value may be used as an identifier for object properties [...] However, when trying to use it as the key property type: type obj = { [key: s ...

Obtain real-time information from an object using React

After developing an app using React, I encountered a scenario where I needed to work with data from an API. Here is the object structure: let currency = { "success": true, "timestamp": 1648656784, "base": "EUR", &quo ...

Configuring a devServer proxy leads to a 404 error

Within my src/vue.config.js file, I have the following configuration: module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8081', changeOrigin: true, }, }, }, }; When I c ...

Navigating through object arrays using a loop

I have multiple arrays within an object that I would like to iterate through using numeric values. This is necessary in order to assign them to different slots in an accordion loop. The JSON file containing the data looks similar to this (Pokemon used as a ...

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...

Prevent the page from scrolling while the lightbox is open

I am struggling with a lightbox that contains a form. Everything is functioning properly, but I need to find a way to prevent the HTML page from scrolling when the lightbox is active. <a href = "javascript:void(0)" onclick=" document.getElementById(& ...

Anticipating the execution of pool.query within a callback function in the Express framework

Within an Express post endpoint, I am utilizing crypto.generateKeyPair. After generating the key pair, I wish to store it in my database and then return the ID of the inserted row within the same endpoint. Here is the code snippet for the endpoint: app.p ...

Unique loading animations are assigned to each individual page within the Next.js framework

Is there a way to have unique loading animations for each of my website pages during the loading process? How can I achieve this? I've attempted to put the loading component on the page component directly, but it doesn't seem to work: //Page com ...

What is the most effective method of utilizing union or extend in TypeScript when faced with a comparable scenario?

I have a function that takes in two different types of objects: const canBeGenericOrDefaultData = { id: 123, pointData: { square: 'x145', triangle: 'y145' } } function submitHandler(canBeGenericOrDefaultData: AllTheDatas | G ...

The console indicates that the state's arrays have been filled, yet I'm unable to retrieve the object[0]

In my code, the functions that populate the state are called on component will mount. When I log the state on the render, this is what I observe in the log. The log clearly shows that the arrays in the state have been populated, although there seems to be ...

Query MySQL and automatically populate form fields with the data retrieved after the user triggers an "onexit" or "onsubmit" event, all without having to reload the page,

Seeking a way to auto-fill form fields with data from MySQL database. The goal is to input a value in a text field, search the database matching that value, and populate the remaining form fields without having to navigate away from the page. If anyone h ...

Is there a way to monitor real-time updates without relying on setInterval or timeout functions?

Currently in the process of building a social network, I am working on fetching live notifications. The current approach involves sending an AJAX request every few seconds using setInterval. The code snippet for this operation is as follows: setInterval ( ...

Using jQuery to dynamically format a date with variables

Looking to properly format a date for use in a compare function to sort data $(xml).find("item").each(function () { var dateText = $(this).find("Date").text(); var year = dateText.substr(0,4); var month = dateText.subst ...

How can I access a component variable within a foreach loop in Typescript?

Can anyone please explain how I can access a component variable within a foreach loop? Check out my code on Plunker public exampleVariable:number; test(){ console.log('fired'); var x =[1,2,3,4]; x.forEach(function (e){ th ...