WebGL

From David's Wiki
\( \newcommand{\P}[]{\unicode{xB6}} \newcommand{\AA}[]{\unicode{x212B}} \newcommand{\empty}[]{\emptyset} \newcommand{\O}[]{\emptyset} \newcommand{\Alpha}[]{Α} \newcommand{\Beta}[]{Β} \newcommand{\Epsilon}[]{Ε} \newcommand{\Iota}[]{Ι} \newcommand{\Kappa}[]{Κ} \newcommand{\Rho}[]{Ρ} \newcommand{\Tau}[]{Τ} \newcommand{\Zeta}[]{Ζ} \newcommand{\Mu}[]{\unicode{x039C}} \newcommand{\Chi}[]{Χ} \newcommand{\Eta}[]{\unicode{x0397}} \newcommand{\Nu}[]{\unicode{x039D}} \newcommand{\Omicron}[]{\unicode{x039F}} \DeclareMathOperator{\sgn}{sgn} \def\oiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x222F}\,}{\unicode{x222F}}{\unicode{x222F}}{\unicode{x222F}}}\,}\nolimits} \def\oiiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x2230}\,}{\unicode{x2230}}{\unicode{x2230}}{\unicode{x2230}}}\,}\nolimits} \)

WebGL, OpenGL on web browsers.

WebGL 1 is based on OpenGL ES 2.0 API.
WebGL 2 is based on OpenGL ES 3.0 API.

Usage (WebGL 1)

Pass arrays as uniforms

Use gl.uniform1fv, ..., gl.uniform4fv to pass an array of floats or vec4. On Javascript, if you are using gl.uniform4fv and want a array of size k in your shader, you will need to pass an array of size 4 * k to the uniform function.

Pass floats as textures

Reference
Example
Oftentimes, you'll want to pass large arrays into your shader.
If you use uniform arrays such as gl.uniform1fv, you'll be limited to 1024 uniforms [1].
If you're using WebGL 2, you can use compute shaders. Note this is built into WebGL 2.

Fetching Texels

You may need to fetch individual pixels of your sampler2D uniforms.
If you're using WebGL2, you can use texelFetch. However, this function is not available in WebGL 1. Instead you will need to set your image to have gl.NEAREST filtering and use texture2D

vec4 texelFetch(int x, int y) {
  return texture2D(tDiffuse, vec2((float(x) + 0.5) / float(width),
                                  (float(height - y) - 0.5) /
                                      float(height)));
}

Usage (WebGL 2)

WebGL 2

WebGL 2 is based on OpenGL ES 3.0 and adds several new features over WebGL 1.
See caniuse to evaluate whether your target browsers support WebGL 2.
As of 2019, Google Chrome, Firefox, and Opera both support WebGL 2.0 even on Android. However, WebGL 2.0 is not supported on iOS and Microsoft Edge (non-chromium version).


Resources