Introduction to WebGL (2)-Hello Word belonging to WebGL

1.demo effect

Insert picture description here
As above, using WebGL to draw a 30px 30px red square on a 400px 400px canvas , it looks simple, but the sparrow is small and complete, covering a lot of knowledge points, let me talk about it carefully.

2. Related knowledge points

2.1 Canvas

Canvas is the canvas. As the name suggests, it is the place for painting. Canvas is defined as a label in HTML5. From then on, front-end developers can use this label and scripting language (JavaScript) to fully use their imagination. Canvas canvas can not only draw two-dimensional graphics, It can also draw three-dimensional graphics.

2.1.1 Get Canvas Object

The Canvas canvas is defined as a label in THML, so we need to get the canvas canvas object through the DOM operation function getElementById() method.

<body>
  <!--canvas标签创建一个宽高均为400像素蓝色背景的画布-->
  <canvas id="webgl" width="400" height="400" style="background-color: blue"></canvas>

  <script>
    //通过getElementById()方法获取canvas画布
    var canvas = document.getElementById('webgl');
  </script>
</body>

2.1.2 Get the context of Canvas

Canvas can draw, but it does not provide drawing methods, but to provide something called context (context) mechanism for drawing, Canvas object provides a method of obtaining a special context, is getContext () , getContext () method not only can get The context of two-dimensional graphics can also get the context of three-dimensional graphics, how to use it according to your needs

//获取上下文-二维
var gl = canvas.getContext('2d');

//获取上下文-三维
var gl = canvas.getContext('webgl');

2.2 Shader

WebGL called depends on the shader (Shader) drawing plotting mechanism, it provides a flexible and powerful way to draw graphics, WebGL all must use it, it is very strong, but also more complex. Shaders are an important harmony mechanism of WebGL. In the encoding process, it is embedded in the JavaScript code in the form of a string.

2.2.1 Shader classification

WebGL two shaders, vertex shader (Vertex shader) and fragment shader (Fragment shader)

  • Vertex shader Vertex shader is a program used to describe the characteristics of a vertex (such as position, size, etc.). A vertex refers to a point, endpoint or intersection in two-dimensional or three-dimensional space.

  • Fragment shader A program that performs a fragment-wise processing (such as lighting). Fragment is a WebGL term and can be understood as pixel

2.2.2 Initialization of the shader

Here you need to know that the WebGL program includes the JavaScript program running in the browser and the shader program running in the WebGL system. The shader program is passed to the WebGL system in the form of a string through Javascript code. Briefly explain, here embodied as a string shader programs using shader languages (GLSL ES) written

2.2.2.1 Shader language data types (in this case)

The data type of the shader language is mentioned here because the language is a strongly typed programming language. When assigning values, the data types of the left and right sides must be the same, otherwise the program will report an error.

  • float means floating point number
  • vec4 denotes a vector consisting of four floating-point
    vector is composed of four components referred to as a homogeneous coordinate , homogeneous coordinates (x, y, z, w ) is equivalent to the three-dimensional coordinates (x / w, y / w , z /w) That is, when you want to convert a three-dimensional coordinate to a homogeneous coordinate, you only need to add a component to it, the value is 1.0

2.2.2.2 Initialization of the vertex shader

The initialization of the vertex shader is actually to assign values ​​to its built-in variables. It has two built-in variables, gl_Position and gl_PointSize.

variable name Types of description
gl_Position vec4 Indicates the vertex position
gl_PointSize float Indicates the size of the dot (number of pixels)

注意:gl_Position变量必须被赋值,否则着色器无法正常工作,gl_PointSize不是必须的,缺省时着色器默认取值1.0

Example of vertex shader initialization

//顶点着色器
var VSHADER_SOURCE = '' +
  'void main(){\n' +
  //设置顶点位置(坐标原点)
  '  gl_Position =vec4(0.0,0.0,0.0,1.0);\n' +
  //设置点的大小(30px)
  '  gl_PointSize=30.0;\n' +
  '}\n';

2.2.2.3 Initialization of the fragment shader

The vertex shader controls the position and size of the point, the fragment shader controls the color of the point, and the fragment shader assigns the color of the point to the built-in variable gl_FragColor

variable name Types of description
gl_FragColor vec4 Specify the color of the fragment (RGBA format)

After assigning a value to this built-in variable, the corresponding point will be displayed in this color. Its type is also vec4, including four floating-point components, which represent the value of RGBA
. Example of fragment shader initialization

//片元着色器
var FSHADER_SOURCE = '' +
  'void main(){\n' +
  //设置片元颜色(红色)
  ' gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n' +
  '}\n';

3. Part of the WebGL API description

3.1 Set the background color gl.clearColor()

You need to set the background color before clearing the drawing area. Once the background color is specified, the background color will reside in the WebGL system and will not change until the next call to gl.clearColor()

函数功能:指定绘图区域的背景色
-----------------------------------------------------------
调用示例:gl.clearColor(red, green, blue, alpha)
-----------------------------------------------------------
参数		
			red		指定红色值(从0.01.0)
			green	指定绿色值(从0.01.0)
			blue	指定蓝色值(从0.01.0)
			alpha	指定透明度值(从0.01.0)
			小于0.0的值会被截断为0.0,大于1.0的值会被截断为1.0
-----------------------------------------------------------			
返回值		无
-----------------------------------------------------------
错  误		无			

3.2 Clear the drawing area gl.clear()

Clearing the drawing area is actually clearing the buffer. There are three types of buffers in WebGL: color buffer, depth buffer, and template buffer.

函数功能:将指定缓存区设置为预定的值-预定的值指的是gl.clearColor()设置的值
-----------------------------------------------------------------------------------
调用示例:gl.clear(buffer)
-----------------------------------------------------------------------------------
参数		
			buffer					指定待清空的缓存区,位操作位|可以用来指定多个缓存区
			gl.COLOR_BUFFER_BIT		代表清空颜色缓存区
			gl.DEPTH_BUFFER_BIT		代表清空深度缓存区
			gl.STENCIL_BUFFER_BIT	代表清空模板缓存区
-----------------------------------------------------------------------------------			
返回值		无
-----------------------------------------------------------------------------------
错  误		INVALID_VALUE			缓存区不是以上三种类型		

If the background color is not specified (the gl.clearColor() function is not called), call gl.clear() directly, then the default value used is as follows

Cache name Defaults related functions
Color buffer (0.0, 0.0, 0.0, 0.0) gl.clearColor(red, green, blue, alpha)
Depth buffer 1.0 gl.clearDepth(depth)
Template buffer 0 gl.clearStencil(s)

3.3 Draw operation gl.drawArrays()

After the shader is established, we are about to draw. gl.drawArrays() is a powerful function that can be used to draw various graphics. The specification of this function is as follows

函数功能:执行顶点着色器,按照mode参数指定的方式绘制图形
--------------------------------------------------------------------------
调用示例:gl.drawArrays(mode, first, count)
--------------------------------------------------------------------------
参数		
			mode		指定绘制的方式,可以接收以下常量符号:
						gl.POINTS,gl.LINES,gl.LINE_STRIP,gl.LINE_LOOP
						gl.TRIANGLES,gl.TRIANGLE_STRIP,gl.TRIANGLE_FAN
			first		指定从哪个点开始绘制-整形数
			count		指定要绘制多少个顶点-整形数
						
			gl.COLOR_BUFFER_BIT		代表清空颜色缓存区
			gl.DEPTH_BUFFER_BIT		代表清空深度缓存区
			gl.STENCIL_BUFFER_BIT	代表清空模板缓存区
--------------------------------------------------------------------------		
返回值		无
--------------------------------------------------------------------------
错  误		INVALID_ENUM			传入的mode参数不是指定参数
			INVALID_VALUE			参数first或count是负数	

4.demo code

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>使用WebGL绘制一个点</title>
</head>

<body>
  <!--canvas标签创建一个宽高均为400像素蓝色背景的画布-->
  <canvas id="webgl" width="400" height="400" style="background-color: blue"></canvas>

  <script>
    //通过getElementById()方法获取canvas画布
    var canvas = document.getElementById('webgl');
    //通过方法getContext()获取WebGL上下文
    var gl = canvas.getContext('webgl');

    //顶点着色器
    var VSHADER_SOURCE = '' +
      'void main(){\n' +
      //设置顶点位置(坐标原点)
      '  gl_Position =vec4(0.0,0.0,0.0,1.0);\n' +
      //设置点的大小(30px)
      '  gl_PointSize=30.0;\n' +
      '}\n';

    //片元着色器
    var FSHADER_SOURCE = '' +
      'void main(){\n' +
      //设置片元颜色(红色)
      ' gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n' +
      '}\n';

    //初始化着色器
    initShader(gl, VSHADER_SOURCE, FSHADER_SOURCE);

    // 设置canvas的背景色
    gl.clearColor(0.0, 0.0, 0.0, 1.0);

    //清空canvas
    gl.clear(gl.COLOR_BUFFER_BIT);

    //开始绘制,绘制顶点,从第一个顶点开始绘制,绘制一个顶点
    gl.drawArrays(gl.POINTS, 0, 1);

    //初始化着色器函数
    function initShader(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
    
    
      //创建顶点着色器对象
      var vertexShader = gl.createShader(gl.VERTEX_SHADER);
      //创建片元着色器对象
      var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
      //引入顶点、片元着色器源代码
      gl.shaderSource(vertexShader, VSHADER_SOURCE);
      gl.shaderSource(fragmentShader, FSHADER_SOURCE);
      //编译顶点、片元着色器
      gl.compileShader(vertexShader);
      gl.compileShader(fragmentShader);

      //创建程序对象program
      var program = gl.createProgram();
      //附着顶点着色器和片元着色器到program
      gl.attachShader(program, vertexShader);
      gl.attachShader(program, fragmentShader);
      //链接program
      gl.linkProgram(program);
      //使用program
      gl.useProgram(program);
      //返回程序program对象
      return program;
    }
  </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/qw8704149/article/details/114224905