Struggling to get a shader up and running on three.js using shaderfrom

Trying to add this shader to my project:

This is the fragment shader code:

<script id="fragmentShader" type="x-shader/x-fragment">
    #ifdef GL_ES
        precision highp float;
        precision highp int;
    #endif

    uniform vec2 u_resolution;
    uniform vec2 u_mouse;
    uniform float u_time;
    uniform sampler2D texture1;

    // Example varyings passed from the vertex shader
    varying vec3 vPosition;
    varying vec3 vNormal;
    varying vec2 vUv;

    void main() {
        vec3 color = vec3(texture2D(texture1, vUv));
        vec3 outcolor=color;
        float v = u_time + (vUv.x*0.5 + vUv.y*0.5);
        vec2 Uv2 = vec2(color.r+color.b+v,color.g+color.b+v);
        outcolor = vec3(texture2D(texture1, Uv2));
        gl_FragColor = vec4( outcolor, 1.0 );

    }
</script>

And here's the vertex shader code:

<script id="vertexShader" type="x-shader/x-vertex">

    varying vec3 vPosition;
    varying vec3 vNormal;
    varying vec2 vUv;

    void main() {

        vNormal = normal;
        vUv = uv;
        vPosition = position;

        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

    }

</script>

The shader compiles but the result is not as expected - instead of the desired effect, I get a highly contrasted image that seems frozen in time. The uniform u_time value is being incremented in a requestAnimationFrame function.

What am I missing? Any help would be appreciated.

Answer №1

I've enhanced your code for compatibility with the latest revision (r96).

Make sure to check the texture settings.

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

var tex = new THREE.TextureLoader().load("https://threejs.org/examples/textures/UV_Grid_Sm.jpg");
tex.wrapS = THREE.RepeatWrapping;
tex.wrapT = THREE.RepeatWrapping;

var geo = new THREE.PlaneBufferGeometry(2, 2);
var mat = new THREE.ShaderMaterial({
  uniforms:{
      time: {value: 0},
      texture1: {value: tex}
  },
  vertexShader:`
    varying vec2 vUv;
    void main() {
      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
    }
  `,
  fragmentShader: `
    uniform float time;
    uniform sampler2D texture1;
    varying vec2 vUv;
    void main() {
      vec3 c = vec3(texture2D(texture1, vUv));
      float v = time + (vUv.x*0.5 + vUv.y*0.5);
      vec2 Uv2 = vec2(c.r + c.b+v, c.g + c.b + v);
      vec3 outcolor = vec3(texture2D(texture1, Uv2));
      gl_FragColor = vec4( outcolor, 1.0 );
    }
  `
});
var plane = new THREE.Mesh(geo, mat);
scene.add(plane);

var clock = new THREE.Clock();
var time = 0;

render();
function render(){
  requestAnimationFrame(render);
  time += clock.getDelta();
  mat.uniforms.time.value = time;
  renderer.render(scene, camera);
}
body{
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/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

How can I use Angular to bind the text entered in an `input` within one `ng-repeat` `div` to another `div` within a different `ng-repeat`?

I am trying to create a dynamic Angular-based webpage where input tags are connected to h3 tags in separate DIVs. Below is the setup of my HTML page (as seen on Plunker): <!DOCTYPE html> <html> <head> <style type="text/css> ...

axios does not distinguish between response and error in its return value

I have created a React component that contains a function called onFormSubmit. This function calls another function from a separate component, which in turn makes a POST request using axios. I want the ability to return a response if the POST request is su ...

Reveal content as you scroll

I'm having trouble with the code snippet below. My goal is to utilize .cbp-fbscroller in my CSS to show a new side navigation menu on my HTML page only when scrolling down to 900px. However, as someone who is new to JavaScript, I am struggling to make ...

Incorporate adjustable div heights for dynamically toggling classes on various DOM elements

One of the challenges in developing a chat widget is creating an editable div for users to input text. In order to maintain the design integrity, the box needs to be fixed to the bottom. An essential requirement is to have javascript detect resizing as us ...

The drop-down menu does not maintain its selected option after the window is refreshed

I am struggling with a dropdown list as shown below: <select class="span2" id ="sort" name= "order_by"> <option >Default</option> <option >Price</option> <option >Color</option> ...

We'll show you the steps to properly organize a set of radio buttons created dynamically within a 'controlgroup' using jQuery Mobile

I am facing an issue with grouping dynamically generated radio buttons into a jQuery Mobile control group. I generate the radio buttons and append them to a div, but they are displayed separately even though the wrapping div contains a 'controlgroup&a ...

Harness the power of JavaScript to generate a dynamic overlay with a see-through image that can be expanded

Within different sections of my website, we display banner ads that are loaded in real-time from third-party sources and come in various sizes. I'm interested in adding a transparent overlay image to each ad which would allow me to trigger a click ev ...

How can datatables format a column by pulling from various sources? (Utilizing server side processing

Struggling to implement server-side processing with concatenated columns and encountering SQL errors. Came across a post discussing the issue: Datatables - Server-side processing - DB column merging Would like to insert a space between fields, is this ac ...

Utilize the power of JavaScript to recursively map object keys

I am working with an array of objects that have varying depths. My goal is to output the names in a specific format: Top Level Top Level > Sub 1 Top Level > Sub 1 > Sub 1-2 Top Level > Sub 2 Unfortunately, I am only able to get the name of th ...

Implementing a function to load HTML pages upon clicking a button with JavaScript

I need help creating a button that loads an HTML page using JavaScript, without redirecting to the page. However, the current code I have is not loading the HTML page as desired. Here is the code snippet in question: <!DOCTYPE html> <html> &l ...

Steps for creating a CodeBlock in a Next.js Website blog similar to the one in the provided image

Learn how to insert a code block in Next.js. def greet(name): """ This function greets the person passed in as a parameter. """ print("Hello, " + name + ". Good morning!") Here is an example of ...

Creating a searchable and filterable singleSelect column in the MUI DataGrid: A step-by-step guide

After three days of working on this, I feel like I'm going in circles. My current task involves fetching data from two API sources (json files) using the useEffect hook and storing them in an array. This array contains a large number of products and a ...

Create an array of various tags using the ngRepeat directive to iterate through a loop

I'm familiar with both ngRepeat and forEach, but what I really need is a combination of the two. Let me explain: In my $scope, I have a list of columns. I can display them using: <th ng-repeat="col in columns">{{ col.label }}</th> This ...

The state in a functional component in React fails to update after the initial axios call

Issue : The value of "detectLanguageKey" only updates after selecting the language from the dropdown twice. Even after selecting an option from the dropdown for the first time, the detectLanguageKey remains empty and is only updated on the second selectio ...

When navigating using the next and back buttons, the active state in Angular is automatically removed

Looking for some assistance with my quiz app setup. Each question has True/False statements with corresponding buttons to select T or F. However, when I click the next/back button, the active class is not being removed from the previous selection. As a beg ...

The Express/Mongoose route consistently modifies the identical item

I'm encountering an issue where any attempt to update or create a new item results in only creating one item and then updating that same item regardless of the input. Is there something incorrect with this route? // @route POST api/item // @desc ...

The localStorage API (getItem/setItem) is not supported with setTimeout

I find it fascinating how these two codes exhibit different behaviors. It's interesting to note that functions like 'console.log' would work in both scenarios, but localStorage API functions such as getItem and setItem do not. setTimeout(()= ...

What is the most efficient method for clearing the innerHTML when dealing with dynamic content?

Is there a more efficient method for cleaning the innerHTML of an element that is constantly changing? I created a function to clean the containers, but I'm not sure if it's the most efficient approach. While it works with the specified containe ...

React not correctly returning multiple values in function: TypeError: cannot iterate over undefined (cannot read property Symbol(Symbol.iterator))

Although there are numerous questions with a similar title, none of them address my specific concern. My current project involves a React app that retrieves data from a backend built with Node.js and MySQL. However, I encountered the following error while ...

Accessing audio files in a directory using ajax

I need assistance with implementing a feature in my mp3 music player code. I want the player to fetch songs from a directory instead of using the page's URL. var songs = [{ { title: 'Blackout City', artist: 'Anamanaguchi&ap ...