Issue with Fragment Shader not appearing in ThreeJS

Seeking assistance with threejs and shader implementation. I am encountering difficulties with displaying a shader, particularly with the variable "len" in the code. I suspect this variable is the root cause of the issue. The codepen link for reference: https://codepen.io/Yerbs/pen/eYWgevO. Any guidance would be greatly appreciated.

fragmentShader: `
    uniform vec2 resolution;
    uniform float time;
    
    const int AMOUNT = 12;
             
            void main() {
        vec2 coord = 20.0 * (gl_FragCoord.xy - resolution / 2.0) / min(resolution.y, resolution.x);
    
        float len;
    
        for (int i = 0; i < AMOUNT; i++){
            len = length(vec2(coord.x, coord.y));

            coord.x = coord.x - cos(coord.y + sin(len)) + cos(time / 9.0);
            coord.y = coord.y + sin(coord.x + cos(len)) + sin(time / 12.0);
        }
    
        gl_FragColor = vec4(cos(len * 2.0), cos(len * 3.0), cos(len * 1.0), 1.0);
            }
        `
    });
    

Prior testing indicates that the issue lies within the fragment shader itself.

Answer №1

To properly utilize the shader material in Three.js, make sure to define the values for the uniforms variables time and resolution as shown below:

const material = new THREE.ShaderMaterial({
    uniforms: {
        time: { type: "f", value: 0.0 },
        resolution: { type: "v2", value: new THREE.Vector2() },
    },
    // [...]
function animate(timestamp) {
    requestAnimationFrame(animate);
    material.uniforms.time.value = timestamp / 1000;
    material.uniforms.resolution.value.x = renderer.domElement.width;
    material.uniforms.resolution.value.y = renderer.domElement.height;
    renderer.render(scene, camera);
}

For a complete example, refer to the code snippet below:

const renderer = new THREE.WebGLRenderer({
    antialias: false
});

renderer.setSize(window.innerWidth, window.innerHeight, 2);
document.body.appendChild(renderer.domElement);
window.addEventListener( 'resize', function(e) {
    renderer.setSize(window.innerWidth, window.innerHeight, 2);
});

const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);

const material = new THREE.ShaderMaterial({
    uniforms: {
        time: { type: "f", value: 0.0 },
        resolution: { type: "v2", value: new THREE.Vector2() },
    },
    vertexShader: `
    varying vec2 vUv;
    
    void main() {
        vUv = uv;
        gl_Position = vec4( position, 1.0 );    
    }
    `,
    fragmentShader: `
    uniform vec2 resolution;
    uniform float time;

    const int AMOUNT = 12;
            
    void main() {
        vec2 coord = 20.0 * (gl_FragCoord.xy - resolution / 2.0) / min(resolution.y, resolution.x);

        float len;

        for (int i = 0; i < AMOUNT; i++){
            len = length(vec2(coord.x, coord.y));

            coord.x = coord.x - cos(coord.y + sin(len)) + cos(time / 9.0);
            coord.y = coord.y + sin(coord.x + cos(len)) + sin(time / 12.0);
        }

        gl_FragColor = vec4(1.0, cos(len * 3.0), cos(len * 1.0), 1.0);
    }
    `
});

const quad = new THREE.Mesh(new THREE.PlaneBufferGeometry( 2, 2, 1, 1 ), material);
scene.add(quad);

function animate(timestamp) {
    requestAnimationFrame(animate);
    material.uniforms.time.value = timestamp / 1000;
    material.uniforms.resolution.value.x = renderer.domElement.width;
    material.uniforms.resolution.value.y = renderer.domElement.height;
    renderer.render(scene, camera);
}

animate();
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dca8b4aeb9b99cecf2edefeb">[email protected]</a>/build/three.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

Tips for maintaining a persistent login session in React Native with Firebase forever

I've been grappling with this issue for a few days now. Essentially, my aim is to have Firebase remember the user so they remain logged in after logging in once. The first block of code is the App component (I've omitted some of the irrelevant co ...

Using HTML and JavaScript to choose relatives from the extended family: Uncles and Aunts

Looking for a better way to target elements in your HTML code? <div class="chunk" id=""> <div class="chunkContent"> <div class="textLeft" ></div> <div class="textRight" ></div> <div class= ...

What is the best way to store a username and password within a JavaScript object in ReactJS?

I am encountering an issue with obtaining the login credentials from the object. Although the code snippet below functions perfectly well with other forms. SignIn.js export default function SignIn(props) { const [state, setState] = useState({ userna ...

What is the best way to find out if multiples of a specific time interval can evenly divide the time between two

I'm currently utilizing Luxon for handling dates and durations. I have two specific dates and an ISO duration, and I am looking to figure out how to determine if the interval between the dates is a multiple of the specified duration without any remain ...

Managing reverted MySQL transactions in a Node.js environment

I've been struggling with an issue for a few days now and I'm really hoping that you could provide some assistance. The problem lies in a node.js API using sequelize to interact with a MySQL database. When certain API calls are made, the code i ...

Transforming specific symbols (é è ë) with URL encoding

I am currently working on a JavaScript function that opens the user's email client with pre-filled content. However, I am facing difficulties in converting special characters so they display correctly in the email client (especially when passed throu ...

Pass information to a PHP file using JavaScript when the form is submitted

Essentially, I am looking to extract values from various inputs and spans using JavaScript when the submit input is clicked. These values will then be sent to PHP using $post in order to ultimately send them via email. Previously, I tested replacing all of ...

Is there a way to verify the availability of an authenticated resource without triggering a pop-up for credentials in the browser?

I am facing the challenge of fetching data from a web service located on a different server without knowing if the user has an active session on that server. If the user does have a session, I want to retrieve the data automatically. However, if they do no ...

Are the files selected by the user not displaying properly in the URL?

I'm currently working on a project using PhoneGap where I am facing an issue with uploading files and adding all file names to the parameters. The desired format is: http://www.example.com/uplaod.html?file=file1,file2,file3 To achieve this, I have a ...

When using Three.js to load a gltf model and applying a color to it, the model appears normal. However, upon zooming out

Greetings to all, I've encountered an unusual issue while working with a glTF model in three.js. When I zoom into the model, it displays colors as expected. However, when I zoom out, the entire model appears black. Interestingly, setting color directl ...

What is the best way to animate a three.js object to the right using GSAP without obstructing the surrounding HTML text?

As a newcomer to web design, I seek forgiveness if my question appears basic. I am working on an animated object in three.js that I want to move to the left side of the screen using GSAP. Additionally, I have a text "Hello" on the left side of the screen. ...

Effortlessly switch between multiple divs with jQuery

I am working on a functionality where multiple divs should be displayed or hidden based on the button clicked. Initially, all buttons and divs are visible. Upon clicking a button, only the corresponding div should be visible. Subsequent clicks on other but ...

Why isn't my div displaying in JavaScript?

Currently working on a project for the Odin Project front-end web development. My task involves creating a grid using javascript/jQuery. I attempted to use the createElement method but have encountered an issue in making the div visible within the html. Am ...

Retrieving data from multiple mongo collections and merging selected attributes from the output

I'm attempting to query a Mongo collection, extract an attribute from each object returned, use that attribute to retrieve data from another collection, and then combine the data. I am unsure of how to achieve this on mongoDB. To break it down, what I ...

I want to utilize a select drop-down menu for navigating between pages in my pagination, breaking away from the traditional method of using <a> tags

I have a select dropdown that is dynamically generated for navigation to other pages within the script. It lists the number of pages available for navigation. However, after selecting a page and loading it, the dropdown does not stay selected. I've tr ...

NodeJS - The server returns a 404 error before ultimately displaying the requested page

I'm having trouble with my nodeJS application. When I make an asynchronous call using ajax, the server first responds with a 404 error before loading the page. The application functions properly, but I keep receiving repetitive logs stating "Can' ...

Tips for optimizing performance by preloading external CSS and JavaScript files from a third-party source in a ReactJS project with webpack

Is there a method similar to using ProvidePlugin for preloading jQuery that can be used to preload third-party CSS and JS files without using import in the entry JS file? The reason I am interested in preloading these files is because I encountered an err ...

Tips on updating a div with jQuery AJAX in my PHP script - help needed!

My jQuery call to PHP is functioning well. However, I am trying to figure out if it's possible to directly output the new content of a specific div from the PHP code using the echo statement. Is this achievable? In the past, I would return the update ...

Navigating through multiple scenes in Three.js

My current challenge lies in implementing a scene transition using three.js. The issue I am facing is that the renderer fails to switch to the new scene as requested. Here's how my setup works: there is an Intro scene with a basic animation that shoul ...

The issue arises when using multiple route files in Route.js, as it hinders the ability to incorporate additional functions within the

After breaking down Route.js into multiple controllers, I'm stuck on why I can't add an extra function to block permissions for viewing the page. // route.js module.exports = function(app, passport) { app.use('/profile&apos ...