Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

p5.js createShader() Method

  • Last Updated : 13 Apr, 2021

The function createShader()  which loads the shaders from strings. it is call  within the function  setup. The easiest way to write shaders as strings in the code  is probably to use javascripts template string syntax.

Syntax :

createShader(vertSrc, fragSrc)

Parameters :

vertSrc :   It is of  String type and it source code for the vertex shader.

fragSrc : It is of String type and it source code for the fragment shader.

Returns :

 A shader object created from the provided vertex and fragment shaders.

Example :

 A shader to show the colour of sunset.


let theShader;
function setup() {
    createCanvas(400, 400, WEBGL);
    // load vert/frag defined below
    theShader = createShader(vertShader, fragShader);
function draw() {
    theShader.setUniform('u_resolution', [width, height]);
    theShader.setUniform('u_time', frameCount*.01);
    // set + display shader
    shader(theShader); // apply shader
    rect(0, 0, 400, 400);
// the vertex shader is called for each vertex
let vertShader = `
    //standard vertex shader
    attribute vec3 aPosition;
    void main() {
      // Copy the position data into a vec4, adding 1.0 as the w parameter
      vec4 positionVec4 = vec4(aPosition, 1.0);
      // Scale to make the output fit the canvas
      positionVec4.xy = positionVec4.xy * 2.0 - 1.0;
      // Send the vertex information on to the fragment shader
      gl_Position = positionVec4;
// the fragment shader is called for each pixel
let fragShader = `
    #ifdef GL_ES
    precision mediump float;
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;
vec3 colorA = vec3(0.905,0.045,0.045);
vec3 colorB = vec3(0.995,0.705,0.051);
    void main() {
     vec2 st = gl_FragCoord.xy/u_resolution.xy;
    float sinF = sin(u_time) * 0.5 + 0.5;
    vec3 colorTop = mix(colorA, colorB, sinF);
    vec3 colorBottom = mix(colorB, colorA, sinF);
    vec3 pct = vec3(st.y);
    vec3 color = vec3(0.0);
    color = mix(colorTop, colorBottom, pct);
    gl_FragColor = vec4(color,1);


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!