What is WebGL

WebGL stands for Web Graphics Library, which stands for Web Graphics Library. Canvas provides two kinds of contexts. The first one is 2D context, which allows us to draw rectangles, arcs, paths, texts and images on canvas. All operations are in a TWO-DIMENSIONAL space. The second is 3D context, which is what we call WebGL. Compared to a 2D context, WebGL provides a three-dimensional space with a richer and more powerful API. WebGL is based on OpenGL ES 2.0, which is a subset of OpenGL 2.0.

How do I get a WebGL context

Just like getting a 2D context, we first get the Canvas element and then call the Canvas getContext method with different parameters. The standard parameter passed to get WebGL is WebGL, but some browsers are experimental-WebGL.

/ / get the canvas
let canvas = document.querySelector("#canvas");

// Get the WebGL context
let gl;
let contextNames = [ "webgl"."experimental-webgl" ];
for (let i = 0; i < contextNames.length; i++) {
    let contextName = contextNames[i];
    gl = canvas.getContext( contextName );
    if (gl) break
}
Copy the code

Composition of WebGL applications

WebGL programs are composed of JavaScript code and shader code.

The JavaScript code is used to control the drawing, and to provide the position, color, and custom information needed for the drawing.

The shader code does the actual drawing. The shader code in turn consists of vertex shader code and slice shader code. The vertex shader determines the position of the vertex and the pixel shader determines the color of the pixel.

shader

The shader code is written in the Shader Language (GLSL), a strongly typed language with a syntax similar to C/C++, and the entire program must have a main function as an entry point.

Vertex shader

The purpose of vertex shader is to calculate the coordinates of each vertex, and each vertex coordinate calculation is to execute the vertex shader code once.

void main() {
    gl_Position = vertexPosition;
}
Copy the code

Slice shader slice

The function of the pixel shader is to calculate the color of the current pixel. Each pixel color calculation executes the pixel shader code once.

void main() {
    gl_FragColor = pixelColor;
}
Copy the code

Gl_Position and gl_FragColor are two built-in variables of GLSL, representing vertex position and pixel color respectively. We need to assign the final computed vertex position and pixel color to these two variables in the two shader codes.

The location of the shader code

Shader code in WebGL is rendered as a string, written in three different ways.

  1. String concatenation

    let vertexShader = 
        "void main() {\n" +
        " gl_Position = vertexPosition; \n" +
        "}\n"
    let fragmentShader = 
        "void main() {\n" +
        " gl_FragColor = pixelColor; \n" +
        "}\n"
    Copy the code
  2. Write it in the script tag

    <script type="x-shader/x-vertex" id="vertexShader">
        void main() {
        	gl_Position = vertexShader;
        }
    </script>
    <script type="x-shader/x-fragment" id="fragmentShader">
        void main() {
        	gl_Position = pixelColor;
        }
    </script>
    <script>
        let vertexShader = document.getElementById("vertexShader").textContent;
        let fragmentShader = document.getElementById("fragmentShader").textContent;
    </script>
    Copy the code

    The type attribute of the script tag is necessary to prevent the contents of the tag from being executed as JS.

  3. Using template Strings

    let vertexShader = `
    void main() {
    	gl_Position = vertexShader;
    }`
    let fragmentShader = `
    void main() {
    	gl_FragColor = pixelColor;
    }`
    Copy the code

The third method, the most recommended, is to write directly to the template string without concatenating it with a plus sign or retrieving a DOM reference first. Eventually these shader code strings are passed to the shader program for execution through the interface provided by WebGL.

About shaders

Shaders are a very complex and important part of graphics. They are very powerful. If you are interested in shaderToy, open this link

You’ll be amazed at how rich and realistic images can be created with just code. Here are a few examples of the really cool shaders I found:

  1. ocean
  2. mountains
  3. Bouncing cartoon characters
  4. Realistic ladybird beetle
  5. The snail

WebGL coordinate system

WebGL adopts Cartesian coordinate system, the origin of which is at the center point of Canvas. Horizontally to the right is the positive direction of the X axis, vertically up is the positive direction of the Y axis, and vertically out of the screen is the positive direction of the Z axis. The range of coordinates is negative 1, 1.

Schematic diagram

A simple example code

Instead of using the shader language, let’s write a simple WebGL example that sets the color to empty the canvas and uses that color to empty the canvas.

The clearColor method is used to set the color of the empty canvas, passing in four parameters representing R, G, B, and Alpha.

The clear method is used for the case canvas, passing the built-in constant gl.color_BUFFer_bit as an argument.

<div class="canvas-container">
    <canvas id="canvas"></canvas>
</div>
Copy the code
let canvas = document.querySelector("#canvas")

// Get the WebGL context
let gl;
let contextNames = [ "webgl"."experimental-webgl" ];
for (let i = 0; i < contextNames.length; i++) {
    let contextName = contextNames[i];
    gl = canvas.getContext( contextName );
    if (gl) break
}

gl.clearColor(0.0.0.1) // The four parameters represent R, G, B, A
gl.clear(gl.COLOR_BUFFER_BIT) // Canvas is cleared with black
Copy the code

The complete sample code is at Github Learning-webgl