當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js js createShader()用法及代碼示例

createShader()函數從字符串加載著色器。它是在函數設置內調用的。將著色器作為字符串編寫為代碼中最簡單的方法可能是使用javascripts模板字符串語法。

用法:

createShader(vertSrc, fragSrc)

參數:

vertSrc:它是String類型,它是頂點著色器的源代碼。

fragSrc:它是String類型,它是片段著色器的源代碼。



返回值:

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

例:

用於顯示日落顏色的著色器。

Javascript


let theShader;
 
function setup() {
    createCanvas(400, 400, WEBGL);
    background(0);
    noStroke();
 
    // 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;
    #endif
     
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);
 
    }`;

輸出

相關用法


注:本文由純淨天空篩選整理自_sh_pallavi大神的英文原創作品 p5.js createShader() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。