)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

WebGL Shader Example

  1. (() => {
  2.  
  3.   const vert = `
  4.     attribute vec3 vec;
  5.     void main(void) {
  6.       gl_Position = vec4(vec, 1.);
  7.     }
  8.   `
  9.  
  10.   const frag = `
  11.     #ifdef GL_ES
  12.     precision highp float;
  13.     #endif
  14.     uniform float time;
  15.     void main(void) {
  16.       vec2 uv = gl_FragCoord.xy  / vec2(500., 500.);
  17.       float w = 1. + cos(uv.y * 60.) * cos(uv.x * 50. + time * 30.);
  18.       gl_FragColor = vec4(uv.x, w * .5, w, 1.);
  19.     }
  20.   `
  21.  
  22.   document.body.style.background = '#000'
  23.   const gl = document.body
  24.     .appendChild(document.createElement('canvas'))
  25.     .getContext('webgl')
  26.  
  27.   Object.assign(gl.canvas.style, {
  28.     position: 'absolute',
  29.     left: 0,
  30.     top: 0
  31.   })
  32.  
  33.   with (gl) {
  34.     const s = 1;
  35.     const verts = [
  36.       -s, -s, 0,
  37.        s, -s, 0,
  38.       -s,  s, 0,
  39.        s,  s, 0,
  40.     ]
  41.  
  42.     const leng = verts.length / 3
  43.     bindBuffer(ARRAY_BUFFER, createBuffer())
  44.     bufferData(ARRAY_BUFFER, new Float32Array(verts), STATIC_DRAW)
  45.  
  46.     const vs = createShader(VERTEX_SHADER)
  47.     shaderSource(vs, vert)
  48.     compileShader(vs)
  49.  
  50.     const fs = createShader(FRAGMENT_SHADER)
  51.     const sp = createProgram()
  52.  
  53.     shaderSource(fs, frag)
  54.     compileShader(fs)
  55.     attachShader(sp, vs)
  56.     attachShader(sp, fs)
  57.     linkProgram(sp)
  58.     useProgram(sp)
  59.  
  60.     const vec = getAttribLocation(sp, 'vec')
  61.     vertexAttribPointer(vec, 3, FLOAT, false, 0, 0)
  62.     enableVertexAttribArray(vec)
  63.  
  64.     onresize = () => {
  65.       const { canvas } = gl 
  66.       canvas.width = innerWidth
  67.       canvas.height = innerHeight
  68.       viewport(0, 0, innerWidth, innerHeight)
  69.     }
  70.  
  71.     onresize()
  72.  
  73.     disable(DEPTH_TEST)
  74.     enable(BLEND)
  75.     blendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA)
  76.  
  77.     const startTime = Date.now();
  78.  
  79.     function loop() {
  80.       const time = (Date.now() - startTime) / 1000
  81.       const uniformTime = gl.getUniformLocation(sp, 'time');
  82.       gl.uniform1f(uniformTime, time);
  83.  
  84.       clearColor(0, 0, 0, 1)
  85.       clear(COLOR_BUFFER_BIT)
  86.       drawArrays(TRIANGLE_STRIP, 0, leng)
  87.       requestAnimationFrame(loop)
  88.     }
  89.     loop()
  90.   }
  91. })()

A basic shader setup. This is realistic minus the use of a with statement…

// 3d // glsl // javascript // shaders // webgl
snippet.zone ~ 2021-24 /// {s/z}