Transforming a Shadertoy experiment into a customized Three.js playground on my local machine

I am currently working on a local shader sandbox project inspired by a Shadertoy created by lennyjpg. I have been referencing two Stack Overflow questions and answers (one, two) for help. The goal is to convert the Shadertoy code to use Three.js for a larger project that already utilizes Three.js. However, despite no apparent errors, I am not getting the expected output. Only the camera helper seems to be displayed. Can anyone identify what mistake I might be making? (Please refer to the runnable snippet provided below.) Appreciate any assistance in advance!

var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var aspect = SCREEN_WIDTH / SCREEN_HEIGHT;

var container;
var clock;
var camera, scene, renderer, mesh;
var cameraOrtho;
var frustumSize = 600;

init();
animate();

function init() {
container = document.createElement('div');
document.body.appendChild(container);

clock = new THREE.Clock();

scene = new THREE.Scene();

cameraOrtho = new THREE.OrthographicCamera(0.5 * frustumSize * aspect / - 2, 0.5 * frustumSize * aspect / 2, frustumSize / 2, frustumSize / - 2, 150, 1000);
cameraOrthoHelper = new THREE.CameraHelper(cameraOrtho);
scene.add(cameraOrthoHelper);

renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container.appendChild(renderer.domElement);

var material = new THREE.ShaderMaterial({

    uniforms: {
        uTime: { value: 0.1 },
        uResolution: { value: new THREE.Vector2(SCREEN_WIDTH, SCREEN_HEIGHT, 1, 1) }
    },

    vertexShader: document.getElementById('vertshader').textContent,
    fragmentShader: document.getElementById('fragshader').textContent
});

mesh = new THREE.Mesh(new THREE.PlaneGeometry(SCREEN_WIDTH, SCREEN_HEIGHT), material);
mesh.position.set(0, 0, 100);
scene.add(mesh);
}

function animate() {
requestAnimationFrame(animate);
update();
render();
}

function update() {
mesh.material.uniforms.uTime.value += clock.getDelta();
}

function render() {
renderer.render(scene, cameraOrtho);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.js"></script>

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

    uniform float uTime;
    uniform vec2 uResolution;
    varying vec2 vUv; 
    
    void main() {
        vUv = uv;
        vec4 mvPosition = modelViewMatrix * vec4(position, 1.0 );
        gl_Position = projectionMatrix * mvPosition;
    }

</script>

<script type="x-shader/x-fragment" id="fragshader">
    
    uniform float uTime;
    uniform vec2 uResolution;
    varying vec2 vUv;

    float f = 0.15, r = 0.4, h=0.5;

    void main() {
        vec2 uvCustom = -1.0 + 2.0 *vUv;
        vec2 ak = abs(gl_FragCoord.xy / uvCustom.xy-0.5);
        
        float g = 1.0/1.618033988749;
        float t = uTime * 0.7 + fract(sin(uvCustom.x+1.0))*2.0;
        float e = 1.0 + sin(uvCustom.x*3.0)*2.6;
        float k =  cos(t - e) + 2.0;
        vec4 tmp  = vec4( abs( sin(t + cos(0.5 * t + (uvCustom.x+t*0.001) * k) ) ));
        float m = sin(uTime*0.37);
        
        if (m > .0) {
            if(uvCustom.y > h){
                tmp = vec4( abs( cos(t + sin(0.5 * t + (uvCustom.x+t*0.001) * k) ) ));
            }
        }

        gl_FragColor  = tmp * smoothstep(ak.x,ak.x+f,r) * smoothstep(ak.y,ak.y+f,r); 
        
        if (m < .0) {
            if (uvCustom.x>1.0) gl_FragColor  = 1.0 - gl_FragColor ;
        }
    }

</script>

Answer №1

Why not experiment without the elaborate shader? Simply adjust your fragment shader to:

void main() {
   gl_FragColor = vec4(1,0,0,1);
}

You may notice that the PlaneGeometry isn't being rendered at all. This is the first issue.

Try modifying the THREE.OrthographicCamera to THREE.Camera and setting the THREE.PlaneGeometry size to 2, 2. You should see red.

Reverting to your original fragment shader may not work, but a basic one like the following does:

    uniform float uTime;
    uniform vec2 uResolution;
    varying vec2 vUv;

    void main() {
        vec2 uv = gl_FragCoord.xy / uResolution;
        gl_FragColor = vec4(uv, 0, 1);
    }

I won't debug your original fragment shader since its purpose is unclear. Try troubleshooting step by step following guidance like this answer to help you decipher the issue.

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

React JS: The active text object in Fabric JS canvas becomes uneditable after attaching an event listener

After implementing event listeners for copy-paste, cut-paste, and movement functionalities in different directions, I encountered an issue when trying to edit the active text object on the canvas. I am utilizing the fabricjs-react module. Below is the cod ...

Troubleshooting the Ui-router refresh problem

I set up my ui-router configuration as follows: app.config(function($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: "/home", templateUrl : 'h ...

Achieve a new line break when the user hits the "Enter" key using HTML and JavaScript

I'm in the process of developing a Chrome Extension that allows users to create a to-do list. My goal is to enable users to submit their task by pressing the "Enter" key, which should move the task to the next line after submission. I am currently fac ...

How can I utilize data retrieved from $http.get in Vue.js once the page has finished loading?

I'm having trouble figuring out how to trigger a function in Vue.js after an $http.get request has completed. In the example below, I want to automatically select an element of foobar right after the page loads, but it only works when there's an ...

Having trouble maintaining the original events on a cloned element

My goal is to duplicate an element passed into a function and retain all associated events, including ones like $('.example').on('click', function(e) ... )} that are defined within the document ready. Here's what I'm trying: ...

Implementing visibility toggles for objects in three.js using a graphical user interface

I am interested in controlling the visibility of objects in my scene through a button on a GUI. The following function currently hides/shows objects individually: g3white.traverse(function(child){child.visible = true;}); g3black.traverse(function(child){ ...

Create a timer that plays music when a button is pressed

My goal is to initiate a timer when a specific button is clicked. While there are many timers available that start upon page load, I have not been able to find one that begins upon clicking a button. Additionally, the timer must start at the same time as ...

Leveraging the csv file functionality in the npm package of d3 version 5

Currently in my react project, I am utilizing d3 for data visualization. After installing the d3 module via npm, I found myself with version 5.9.2 of d3. The challenge arose when attempting to use a csv file within d3. Despite scouring various resources, I ...

Why is AngularJS redirection not retrieving the value from window.localStorage?

After utilizing local storage, I encountered an issue where upon logging in and being redirected to the myprofile page, the local storage value was not loading properly. Instead, I was getting a null value. It wasn't until I manually reloaded the page ...

Leverage React.js by incorporating a Header-Imported JavaScript Library

I recently developed a React.js web application and am exploring the use of Amplitude Analytics, which provides a Javascript SDK found here. According to the guidelines, I need to include a <script></script> within the <head></head> ...

Issue with React Router functionality not functioning

I am currently facing an issue with my react-router setup. You can find the code I am using by visiting this link - https://github.com/rocky-jaiswal/lehrer-node/tree/master/frontend Although it is a basic setup for react-router, I am experiencing difficu ...

To enhance your React Class Component, make sure to utilize the withStyles feature when

This particular component is not set as a default export component. I am attempting to apply some styles to it but struggling to figure out how to encapsulate it in an HOC. Hence, the current issue where it does not recognize the classes variable. import ...

Scroll upwards within a nested div

Is there a way to smoothly animate the content of the inner div upward without requiring any button clicks? Also, is there a method to trigger an event once the animation has completed? ...

What is the purpose of using double quotes within single quotes in JavaScript?

Could someone clarify the reason behind needing to nest double quotes inside single quotes in my Webpack configuration shown below? What is preventing using just double quotes? module.exports = merge(prodEnv, { NODE_ENV: '"development"', API ...

Insert analytics code post-button click permission granted in Next.js/React

Need help with activating analytics scripts upon a button click? I have analytics scripts that I want to add to my next.js website only if the user opts in. When a button in my CookieBanner component is clicked, a cookie is set to track if the user has o ...

What is the method for retrieving post ID with the Google Feed API?

I am currently utilizing two different JS codes to dynamically load posts from my Wordpress website: Code 1: JSON API <script src="http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=listPosts" type="text/javascript">& ...

What steps are involved in implementing Local fonts in theme UI for Next JS?

I am currently developing an application using next JS with [theme-UI][1]. However, I need to implement local or custom fonts in my project and I'm unsure of how to do this. Below is the current theming setup: const theme = { fonts: { ...

What are some solutions for repairing unresponsive buttons on a webpage?

My task is to troubleshoot this webpage as the buttons are not functioning correctly. Here’s a snippet of the source code: <!DOCTYPE html> <html lang="en"> <head> ... </head> <body> <div id="container" ...

Does utilizing this.someFunction.bind(this) serve a purpose or is it duplicative

As I analyze someone's code, I stumbled upon the following snippet: this.device_name.changes().onValue(this.changeName.bind(this)) My interpretation so far is that onValue requires a callback function, which in this case is this.changeName.bind(this ...

Arranging a 2D array of matchups to ensure an equal distribution of home and away matches for each team

I am in the process of developing a unique UEFA Champions League 24 'Swiss Model' tournament with 36 teams. Each team is set to compete against 8 different opponents, resulting in a total of 144 matches. I already have a list of matchups prepared ...