Implement a Basic Custom Shader on a Cube in Three.js

Struggling with applying a basic custom shader to a cube in Three.js. Whenever I attempt to use the shader, the cube mysteriously vanishes. No issues when using a standard Toon or Lambert Material - cube rotates and behaves as expected.

Oddly, Orbit Controls cease to function when the custom shader is applied. Despite studying numerous examples, I can't seem to figure it out.

// Setting up the Scene
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.z =3;

// Creating Light
var light = new THREE.PointLight(0xFE938C, 1.5);
light.position.set(0,5,20);
scene.add(light);

var geometry = new THREE.BoxGeometry(1, 1, 1);

var uniforms = {
    u_time: {type: 'f', value: 0.2},
    u_resolution: {type: 'v2', value: new THREE.Vector2()},
};

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

var cube = new THREE.Mesh(geometry, material);
cube.position.set(0, 0, 0);

scene.add(cube);

var renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

controls = new THREE.OrbitControls(camera, renderer.domElement);

var render = function() {
requestAnimationFrame(render);

renderer.render(scene, camera);
};

render();
<script id="vertexShader" type="x-shader/x-vertex">
    void main() {
            gl_Position = vec4(position, 1.0);
        }
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
    uniform vec2 u_resolution;
    uniform float u_time;

        void main() {
            vec2 st = gl_FragCoord.xy/u_resolution.xy;
            gl_FragColor = vec4(st.x, st.y, 0.0, 1.0);
        }
</script>

Answer №1

To create a realistic 3D scene using Three.js, it is essential to utilize a vertex shader that incorporates the projection matrix and model view matrix provided by Three.js.

    void main() {
            gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
        }

//Setting up the Scene
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 3;

//Adding Light Source
var light = new THREE.PointLight(0xFE938C, 1.5);
      light.position.set(0,5,20);
      scene.add(light);

var geometry = new THREE.BoxGeometry( 1, 1, 1 );

 var uniforms = {
    u_time: {type: 'f', value: 0.2},
    u_resolution: {type: 'v2', value: new THREE.Vector2()},
  };
  
var material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent
});
        

var cube = new THREE.Mesh( geometry, material );
cube.position.set(0, 0 , 0);

scene.add( cube );

var renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize( window.innerWidth, window.innerHeight);
document.body.appendChild( renderer.domElement );

var render = function () {
requestAnimationFrame( render );

        uniforms.u_resolution.value.x = window.innerWidth;
        uniforms.u_resolution.value.y = window.innerHeight;
        
cube.rotation.x += 0.1;
cube.rotation.y += 0.005;

renderer.render(scene, camera);
};

render();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/86/three.min.js"></script>
<script id="vertexShader" type="x-shader/x-vertex">
    void main() {
            gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
        }
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
 uniform vec2 u_resolution;
 uniform float u_time;

        void main() {
            vec2 st = gl_FragCoord.xy/u_resolution.xy;
            gl_FragColor=vec4(st.x,st.y,0.0,1.0);
        }
</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

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...

Update issue with Three.js mixer not responding to 'setTime' command

I've configured my threejs animation mixer like this: this.mixer = new THREE.AnimationMixer(this.object); this.mixer.timeScale = 2; //play at double speed this.mixer.addEventListener('finished', this.handlePullAnimFinished); this.pullAnim = ...

403 Forbidden error encountered while making a REST API call using jQuery AJAX

Attempting to create a basic jQuery ajax call to an API Here is the code I'm using: jQuery.ajax({ type: "GET", url: "http://example.com/api/v1/testapi", headers: { "Authorization": "Basic Ylc5aWXXXXXXlk1ucWx5ZnA=" }, success: fu ...

The function(result) is triggered when an http.get request is made

Can anyone help me figure out why my function is jumping after completing the request? It seems to be skipping over .then(function(result){ }. I suspect that the issue might be related to the <a> element with an onclick attribute containing an href ...

Invoking AJAX function post readystatechange

Currently, I am in the process of making an Ajax call to a server and attempting to invoke another function once the response is ready (readystatechanged). As of now, there isn't any serverside code implemented. Surprisingly, Chrome and Firefox encoun ...

What could be causing the shake effect on the MUI dialog to not work when clicking away?

I am trying to implement a shake effect when the user clicks outside the MUI dialog to indicate that clicking away is not allowed. However, the code I have so far does not seem to be working as the effect is not being applied. Can someone please help me ...

Tips for incorporating dynamic parameters/variables into templates displayed using ng-bind-html or a custom directive (within ng-repeat)

EDIT: I have created a solution sample based on the initial answer. However, I am open to further suggestions and would appreciate any help in filling the gaps in my knowledge (please refer to the comments). plnkr.co/edit/mqGCaBHptlbafR0Ue17j?p=preview OR ...

How to Implement Click Actions on Elements in AngularJS

Just starting out with angularjs and I have a scenario with jQuery. handleClick(); function handleClick() { var doubleClick = false; $('#text span.word').on('click', function() { var that = this; setTimeout(funct ...

Jquery allows for the toggling of multiple checkboxes

I have a group of check-boxes that I would like to toggle their content when checked. Currently, I am using jQuery to achieve this functionality, but I am searching for a way to optimize my code so that I do not need to write a separate function for each ...

Automatically identify the appropriate data type using a type hint mechanism

Can data be interpreted differently based on a 'type-field'? I am currently loading data from the same file with known type definitions. The current approach displays all fields, but I would like to automatically determine which type is applicab ...

What is the best way to exclude React.js source files from a fresh Nest.js setup?

My setup includes a fresh Nest.js installation and a directory named "client" with a clean create-react-app installation inside. Here is the project structure: ./ ...some Nest.js folders... client <- React.js resides here ...some more Nest.js fo ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

Typescript indicates that an object may be potentially null

I've hit a roadblock where I keep getting warnings that the objects might be null. After searching online and on StackOverflow, I've tried numerous solutions with no luck. My goal is to insert the text "test" into the HTML elements using their ID ...

Every time I try to loop through my JSON object using an $.each statement, an error is thrown

When I execute an $.each loop on my json object, I encounter an error 'Uncaught TypeError: Cannot read property 'length' of undefined'. It seems that the issue lies within the $.each loop as commenting it out results in the console.log ...

Display a span element using jQuery datatable to indicate that the update operation was

I have implemented inline editing using jQuery Datatables. Currently, I am trying to display a green checkmark when a record gets updated. Below is the ajax call that populates the table: $.ajax({ url: 'api/massEditorSummary.php', type: &ap ...

Identifying the precise image dimensions required by the browser

When using the picture tag with srcset, I can specify different image sources based on viewport widths. However, what I really need is to define image sources based on the actual width of the space the image occupies after the page has been rendered by th ...

Ways to include a CSS file path in a link tag from an npm package

I have recently installed a package using npm. npm install lightgallery Now, I am trying to fill the href attribute of a link with the css file directory of this package. Here is what I have so far: <link rel="stylesheet" href="/node_mod ...

What is the best way to check if an object exists in an array in JavaScript and update it if it does, otherwise add it as a new object in

I am working with an array of objects const target = [{name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fafbe2c9eee4e8e0e5a7eae6e4">[email protected]</a>', selected: false, alertType: 'max&ap ...

Tips for Implementing a "Please Hold On" Progress Bar in ASP.NET

I have a master page named siteMaster.master, an aspx page called submission.aspx, and a user control named attachment.ascx. The script manager is included in my master page. The submission page inherits the master page and registers the user control attac ...

Is there a way to continually update a specific portion of a webpage using AJAX without manual intervention?

$messages = $db->query("SELECT * FROM chatmessages ORDER BY datetime DESC, displayorderid DESC LIMIT 0,10"); while($message = $db->fetch_array($messages)) { $oldMessage[] = $message['message']; } $oldMessages = array_reverse($oldMessage ...