Exploring Shadertoy's Visual Magic with THREE.js

I am currently attempting to implement this shader on a canvas using THREE.js: . The function I am using usually works for simpler shaders, but for this one, I might need to save the floats as uniforms. I am a bit stuck on this issue. Has anyone encountered a similar problem and knows what might be causing it? I have been following this guide for reference:


        const canvas = document.querySelector('#background');
        const renderer = new THREE.WebGLRenderer({ canvas });
        renderer.autoClearColor = false;

        const camera = new THREE.OrthographicCamera(
            -1, // left
            1, // right
            1, // top
            -1, // bottom
            -1, // near,
            1, // far
        );
        const scene = new THREE.Scene();
        const plane = new THREE.PlaneBufferGeometry(2, 2);

        const fragmentShader = `
            #include <common>

            uniform vec3 iResolution;
            uniform float iTime;

            // Shader code...
        `;

        const uniforms = {
            iTime: { value: 0 },
            iResolution: { value: new THREE.Vector3() },
        };

        const material = new THREE.ShaderMaterial({
            fragmentShader,
            uniforms,
        });

        scene.add(new THREE.Mesh(plane, material));

        // Resize function and rendering logic...
    

Answer №1

The specified iResolution uniform is incorrectly set. It appears to be a simple typo in the code where canvas.height should be used instead of canvas.heigth:

uniforms.iResolution.value.set(canvas.width, canvas.heigth, 1);

uniforms.iResolution.value.set(canvas.width, canvas.height, 1);

const fragmentShader = `
#include <common>

uniform vec3 iResolution;
uniform float iTime;

float ltime;

float noise(vec2 p)
{
  return sin(p.x*10.) * sin(p.y*(3. + sin(ltime/11.))) + .2; 
}

mat2 rotate(float angle)
{
  return mat2(cos(angle), -sin(angle), sin(angle), cos(angle));
}


float fbm(vec2 p)
{
  p *= 1.1;
  float f = 0.;
  float amp = .5;
  for( int i = 0; i < 3; i++) {
    mat2 modify = rotate(iTime/50. * float(i*i));
    f += amp*noise(p);
    p = modify * p;
    p *= 2.;
    amp /= 2.2;
  }
  return f;
}

float pattern(vec2 p, out vec2 q, out vec2 r) {
  q = vec2( fbm(p + vec2(1.)),
    fbm(rotate(.1*iTime)*p + vec2(3.)));
  r = vec2( fbm(rotate(.2)*q + vec2(0.)),
    fbm(q + vec2(0.)));
  return fbm(p + 1.*r);

}

vec3 hsv2rgb(vec3 c)
{
    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}

void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
  vec2 p = fragCoord.xy / iResolution.xy;
  ltime = iTime;
  float ctime = iTime + fbm(p/8.)*40.;
  float ftime = fract(ctime/6.);
  ltime = floor(ctime/6.) + (1.-cos(ftime*3.1415)/2.);
  ltime = ltime*6.;
  vec2 q;
  vec2 r;
  float f = pattern(p, q, r);
  vec3 col = hsv2rgb(vec3(q.x/10. + ltime/100. + .4, abs(r.y)*3. + .1, r.x + f));
  float vig = 1. - pow(4.*(p.x - .5)*(p.x - .5), 10.);
  vig *= 1. - pow(4.*(p.y - .5)*(p.y - .5), 10.);
  fragColor = vec4(col*vig,1.);
}

void main() {
    mainImage(gl_FragColor, gl_FragCoord.xy);
}
`;

function main() {
    const canvas = document.querySelector('#background');
    const renderer = new THREE.WebGLRenderer({canvas});
    renderer.autoClearColor = false;

    let camera = new THREE.OrthographicCamera(
       -1, // left
        1, // right
        1, // top
       -1, // bottom
       -1, // near,
        1, // far
    );
    camera.position.z = 1;

    const scene = new THREE.Scene();
    const plane = new THREE.PlaneBufferGeometry(2, 2);

    const uniforms = {
        iTime: { value: 0 },
        iResolution:  { value: new THREE.Vector3() },
    };

    const material = new THREE.ShaderMaterial({
        fragmentShader,
        uniforms,
    });
     scene.add(new THREE.Mesh(plane, material));

    function resizeRendererToDisplaySize(renderer) {
        const canvas = renderer.domElement;
        const width = canvas.clientWidth;
        const height = canvas.clientHeight;
        const needResize = canvas.width !== width || canvas.height !== height;
        if (needResize) {
        renderer.setSize(width, height, false);
        }
        return needResize;
    }

    function render(time) {

        time *= 0.001;

        resizeRendererToDisplaySize(renderer);

        const canvas = renderer.domElement;
        uniforms.iResolution.value.set(canvas.width, canvas.height, 1);
        uniforms.iTime.value = time;

        renderer.render(scene, camera);

        requestAnimationFrame(render);
    }

    requestAnimationFrame(render);
}

main();
#background{
background : black;
color : white;
  margin: auto;
width : 500px;
height : 500px;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06726e746363463628373733">[email protected]</a>/build/three.js"></script>
<div><canvas id="background"></canvas></div>

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

Enhancing features with jQuery's .animate() function

Can anyone help me figure out why the div on the right is not pushing itself away from the one on the left when I hover over it? I want it to move on mouseenter and return to its original position on mouseleave. The changing background colors are just ther ...

Guide to implementing a slider in HTML to adjust the size of my canvas brush

Hey there, I'm looking to implement a slider functionality under my canvas that would allow users to change the brush size. Unfortunately, all my attempts so far have been unsuccessful. Can anyone lend a hand? Much appreciated! <canvas i ...

Placing files in the "Dist" folder is causing an issue by disrupting the functionality of the Angular 2 app

For testing my login component in Angular2, I am using a mockBackend within my app. Initially, the standalone version of the login worked perfectly fine. However, when trying to integrate it into my ongoing development project, I encountered an issue. Duri ...

Is there a way to use AJAX for transferring a value?

I am looking to transmit a value to a php-script (servo.php) that will then write the received data in a file (/dev/servoblaster). The script section of my HTML file (index.html): <script> function tiltt() { var tilt = document.getElementById("tilt ...

Having trouble with integrating user input from HTML into a JavaScript file to execute a GET request

I am currently working on a project to create a website that integrates the google books API for users to search for books. To start, I have set up a server using express in index.js at the root of the project directory, and all my static files are stored ...

Tips for extracting popular song titles from music platforms such as Hungama or Saavn

I am looking to retrieve the names of the top trending songs/albums from platforms such as Hungama or Saavn. I experimented with web scraping packages available on npm to extract data from websites, including cheerio, jsdom, and request. Eventually, I came ...

Gatsby causing issues with Material UI v5 server side rendering CSS arrangement

I shared my problem on this GitHub issue too: https://github.com/mui-org/material-ui/issues/25312 Currently, I'm working with the Gatsby example provided in Material UI v5: https://github.com/mui-org/material-ui/tree/next/examples/gatsby After imple ...

The Three.js raycaster fails to intersect with objects once they have been displaced from their original position

I am encountering an issue with the raycaster: When I place an object at the origin (0, 0, 0), the raycaster can detect it. However, if I move the object to a different position, like (0, 300, 0), the raycaster no longer hits the object. I have double-ch ...

Bidirectional Data Binding in AngularJS

In my angular application, there is a dropdown with various values. When a user selects a specific value from the dropdown, I want to display the complete array corresponding to that value. <!doctype html> <html lang="en"> <head> < ...

Achieve horizontal wrapping of div elements

Currently, I am developing a blog where search results for articles will be displayed within divs. The design of the website is completely horizontal, meaning that articles scroll horizontally. Creating a single line of divs is straightforward, but it&apo ...

React Three Fiber Video Component pauses automatically after detecting no movement for a short period

I am encountering an issue with my React Three Fiber application where the player movement stops working after being idle for more than 3 seconds. The camera can still be moved around, but the keyboard controls for player movement become unresponsive. Belo ...

What is the best way to loop through JSON properties and then assign their values to elements within an array?

After searching for solutions similar to my goal, I have yet to find one that fits exactly what I need. JSON is still new to me, so any guidance is welcome. In my ASP.NET MVC 5 application, the Web API controller returns the following JSON: { "id": ...

Slick Slider - Defining the Initial Slide

My website features a dynamic carousel showcasing a basketball team's schedule, with games sorted by date for the current season. I am trying to align the slider to display the upcoming game at the center. How can I designate a specific slide as the ...

Load custom JS with Google

I have integrated the Google Ajax API and now I need to load custom javascript that relies on the libraries loaded by the ajaxapi. What is the best way to accomplish this? ...

Arrange the table by adding and editing before and after appending

I have a table data that needs to be dynamically appended. But I want to allow users to add new data using text input and also edit the existing data before and after it's appended. The problem is that when I append new data, it overwrites the previo ...

Issue encountered with the Selenium JavaScript Chrome WebDriver

When it comes to testing an application, I always rely on using Selenium chromewebdriver. For beginners like me, the starting point was following this insightful Tutorial: https://code.google.com/p/selenium/wiki/WebDriverJs#Getting_Started After download ...

Utilizing Flask's get and post methods in conjunction with AJAX integration

I am in the process of developing a food calorie web application and would like to extract data from a MongoDB database into an HTML table. This is my python code: from flask import Flask from flask import request import requests from wtforms import Form ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

Guide to setting up parameterized routes in GatsbyJS

I am looking to implement a route in my Gatsby-generated website that uses a slug as a parameter. Specifically, I have a collection of projects located at the route /projects/<slug>. Typically, when using React Router, I would define a route like t ...

Learn how to create a logarithmic scale graph using CanvasJS by fetching data from an AJAX call

window.onload = function() { var dataPoints = []; // fetching the json data from api via AJAX call. var X = []; var Y = []; var data = []; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.overrideMimeType("applicatio ...