14 Feb 2021

How to use Costom Shader in three.js?


In this post We will try to know that How can we use Own costom Shader (Vertex and fragment Shader) in three.js project?
little bit, if you are already familiar with GLSL ( OpenGL Shading Language). then I could be easier to understand this post.
GLSL use similar Syntax like C Programing Language.

Follow the following step to Add Costom Shader to your threejs.

if You are going to add Costom Shader to your three.js . You need two write two types of Shader.

1. Vertex Shader

Create a Script tag under your HTML page with two attribute :- type & id. these 2 attributes are essential.


<script type="x-shader/x-vertex" id="vertexShader"> // Put the Vertex Shader code here
        
        void main() {
        
         gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); 

         }
        
         </script>

2. Fragment shader

Similar, To above on shader. create second script tag under Your HTML page. script should have attributes type & id.

    <script type="x-shader/x-vertex" id="fragmentShader"> 
    void main(){
    
    vec2 fa = gl_FragCoord.xy / vec2(400.0,400.0);
        
        gl_FragColor = vec4(fa,0,1);
    }
    
    </script>
    

Applying Costom Shader to threejs Mesh object.

In Threejs, Every mesh have own threejs's material. Now, we have to add above defined Costom Shaders (Vertex & Fragment shader) to threejs material of a specific Threejs Mesh Object.

In Threejs for Costom Shader, Have predefined material type - THREE.ShaderMaterial.


   var material = new THREE.ShaderMaterial({ 
   
   vertexShader: document.getElementById( 'vertexShader' ).textContent, 
   
   fragmentShader: document.getElementById( 'fragmentShader' ).textContent 
   
   } );
    
    mesh = new THREE.Mesh( new THREE.IcosahedronGeometry( 20, 4 ), material ); 
    s.add( mesh ); 

    

Read this, How to start with threejs basic setup?
→ Getting started with Threejs.


Reaction:

No comments:

No Comments

COMMENT FROM MESSAGE