Boilerplate code
This HTML page is used as a template for the sample entries that follow.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Draw a point (1)</title>
</head>
<body onload="main()">
<canvas id="webgl" width="400" height="400">
Please use a browser that supports "canvas"
</canvas>
<script src=".. /lib/webgl-utils.js"></script>
<script src=".. /lib/webgl-debug.js"></script>
<script src=".. /lib/cuon-utils.js"></script>
<script src="HelloPoint1.js"></script>
</body>
</html>
Copy the code
Among them, webgl-utils.js, webgl-debug.js, cuon-utils.js, etc., are the supporting tools and methods of this book.
Relevant source code I have made a collection, can be downloaded here. The source code involved in the WebGL Programming Guide book
Shortest WebGL program: Empty drawing area
function main() {
// Get the
var canvas = document.getElementById('webgl');
// Get the WebGL drawing context
var gl = getWebGLContext(canvas);
if(! gl) {console.log('Failed to get the rendering context for WebGL');
return;
}
// Set the background color
gl.clearColor(0.0.0.0.0.0.1.0);
// Clear the color buffer
gl.clear(gl.COLOR_BUFFER_BIT);
}
Copy the code
Here’s a look at the methods involved:
Gets the WebGL drawing context
You can get it directly using Canvas.getContext (‘webgl’), but this may vary from browser to browser, so this book wraps a getWebGLContext() method to get it.
Specifies the background color of the drawing area
// All parameters are from 0 to 1.
gl.clearColor(red, green, bule, alpha);
Copy the code
Once the background color is specified, it is stored in the WebGL system and will not be changed until the next call to the gl.clearcolor () method.
Empty canvas
/** * clears the specified buffer to the default value. If the color buffer is cleared, the default value specified by gl.clearcolor () is used. *@param {*} Buffer specified stay empty buffer, can use | to specify more than one. * GL.color_BUFFer_bit Color buffer * GL.depth_BUFFer_bit Depth buffer * gl.stencil_buffer_bit template buffer */
gl.clear(buffer);
Copy the code
When this method is called, the drawing area is emptied with the previously specified background color. Just clear the color buffer, not the Canvas drawing area.
WebGL has multiple buffers, and gl.color_buffer_bit refers to the color buffer, using the color specified by gl.clearcolor (); The depth buffer gl.depth_buffer_bit is used when drawing 3d graphics; Gl.stencil_buffer_bit is not covered in this book.
Draw a point
Before drawing, it’s important to know that WebGL relies on a drawing mechanism called a shader. Shaders provide a powerful way to draw two-dimensional or three-dimensional graphics. They are powerful, but also complex. We’ll look at shaders step by step later.
// Vertex shader
var VSHADER_SOURCE = Void main() {gl_Position = vec4(0.0, 0.0, 0.0, 1.0); // set vertex coordinates gl_PointSize = 10.0; // Set point size} ';
// Chip shader
var FSHADER_SOURCE =Void main() {gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // Set the color} ';
function main() {
// Get the
var canvas = document.getElementById('webgl');
// Get the WebGL drawing context
var gl = getWebGLContext(canvas);
// Initialize the shader
initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)
// Set the background color
gl.clearColor(0.0.0.0.0.0.1.0);
// Clear the color buffer
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw a point
gl.drawArrays(gl.POINTS, 0.1);
}
Copy the code
Running effect
What is a shader?
The shader we are using now is embedded in a JavaScript program as a string. Webgl requires two types of shaders:
- Vertex shader: A Vertex shader is a program that describes Vertex properties (position, size). A vertex is a point in two – or three-dimensional space.
- Fragment shader: A Fragment shader is a program that processes, for example, lighting, Fragment by Fragment. A slice is a WebGL term that can be understood as a pixel.
Let’s take a look at the process from executing the JavaScript program to the browser displaying the results:
The results can be described as follows:
- Run JavaScript programs and mobilize webGL-related methods;
- Execute vertex shaders and slice shaders to draw in color buffers
- Clear buffer
- The contents of the color buffer are displayed in CANva
Shader program
Shader programs are written using C – like OpenGL ES (GLSL ES). The examples in this book are all shader program code stored in variables as strings.
Initialize the shader
InitShaders () is a helper function provided in this book that initializes shaders and is implemented in the lib/cuon-utils.js file for those interested. However, as a beginner, you don’t have to worry about the details for a while. After you are familiar with WebGL, you can go back and learn the knowledge involved in detail.
Now all we need to know is that by calling this method, passing in the context, the vertex shader code string, the fragment shader code character, we can initialize the shader.
After initializing the shader, the shader is set up and ready to use in the WebGL system. When drawing, the vertex shader executes first, assigning values to the gl_Position and gl_PointSize variables and passing them into the slice shader, which then executes. In fact, the pixel shader receives the pixel values after rasterization, which can be simply understood as the two variables passing from the vertex shader to the pixel shader.
Note: The shader program runs in a WebGL system, not a JavaScript program
Vertex shader
Shader programs, like C programs, need a main() function. We also see two special variables, gl_Position and gl_PointSize. Both variables are built into the vertex shader, where:
gl_Position
Denotes the position of the vertex. This variable must be assigned otherwise the shader will not be able to executevec4
;gl_PointSize
Represents the size of the point, optionally unassigned, default to 1.0, of typefloat
.
GLSL ES is a strongly typed programming language:
- Vec4 represents a vector composed of four floating point numbers and can be created using VEC4 (v0, v1, v2, v3).
- Float indicates a floating point number.
Chip shader
The vertex shader controls the position and size of the point, and the fragment shader controls the color of the point. The role of the slice shader is to process the slice and display it on the screen.
The slice shader assigns the color of the point to the gl_FragColor variable, which is the only built-in variable in the slice shader and controls the final color of the pixels displayed on the screen. The type is VEC4.
Drawing operations
Gl.drawarray () is a powerful method for drawing all kinds of graphics.
/** * Executes the vertex shader, drawing as specified by the mode parameter *@param {*} Mode Drawing mode. gl.POINTS gl.LINES gl.LINE_STRIP gl.LINE_LOOP gl.TRIANGLES gl.TRIANGLE_STRIP gl.TRIANGLE_FAN *@param {int} What vertex does first start drawing * from@param {int} Count Number of draws */
gl.drawArrays(mode, first, count);
Copy the code
In our example, we just have to draw a point. So the first argument is set to gl.points; The second is set to 0 to start from the first vertex; The third parameter is set to 1 to draw only once, that is, a point.
WEBGL coordinate system
Webgl uses a three-dimensional coordinate system with X-axis, Y-axis and Z-axis:
- The positive direction of the x axis is horizontal to the right, the positive direction of the Y axis is horizontal to the up, and the positive direction of the Z axis is external.
- Canvas center point is (0.0, 0.0, 0.0)
- The lower edge of the canvas edge and to (0.0, 1.0, 0.0), (0.0, 1.0, 0.0);
- Canvas left edge and right edge (1.0, 0.0, 0.0), (1.0, 0.0, 0.0);