This article refers to the WebGL Programming Guide
Using the knowledge from the previous chapter, draw the following points:
Source:
Test.js
functionMain () {varGL =Init (); if(!GL) {Console.log (' Failed to Init '); return; } varn =initvertices (GL); if(N < 0) {Console.log (' Failed to init vertices '); return; } gl.drawarrays (GL. POINTS,0, n);}//@Func: init the WebGL//@Return: GL (the WebGL context)functionInit () {varCanvas = document.getElementById (' WebGL '); varGL =getwebglcontext (canvas); if(!GL) {Console.log (' Failed to get the rendering context for WebGL '); return NULL; } if(!initshaders (GL, Vshader_source, Fshader_source)) {Console.log (' Failed to init shader '); return NULL; } gl.clearcolor (0.0, 1.0, 1.0, 1.0); Gl.clear (GL. Color_buffer_bit); returnGL;}//@Func: init vertices//@Return: N ( the number of vertex)functionInitvertices (GL) {varVertexBuffer =Gl.createbuffer (); if(!vertexbuffer) {Console.log (' Failed to create vertex buffer '); return-1; } gl.bindbuffer (GL. Array_buffer, VertexBuffer); varn = 6; varvertices =NewFloat32array ([-0.6,0.3, -0.3,-0.3, 0.0,0.3, 0.3,-0.3, 0.6, 0.3, 0.9,-0.3 ]); Gl.bufferdata (GL. Array_buffer, vertices, GL. Static_draw); varAPos = Gl.getattriblocation (Gl.program, ' APos '); if(APos < 0) {Console.log (' Failed to get APos '); return-1; } gl.vertexattribpointer (APos,2, GL. FLOAT,false, 0, 0); Gl.enablevertexattribarray (APos); returnN;}
View Code
Shader.js
// vertical shader var vshader_source = "attribute Vec4 APos; void main () {gl_position = APos; Gl_pointsize = 30.0; } '
View Code
To draw polygons with these points, the magic lies in the Gl.drawarrays (type, start, count) function, where type can take the following values
(1) GL. POINTS
(2) GL. LINES
Take two points at a time, draw straight lines, i.e. (V0, v1), (v2, v3) ...
(3) GL. Line_strip
First take two points to draw a straight line, after each fetch a point, with the previous line, namely (V0, V1), (v1, v2) ...
(4) GL. Line_loop
In GL. Based on Line_strip, the first point and the last point are connected into lines, i.e. (V0, v1), (v1, v2) ... (VN, V0)
(5) GL. Triangles
Take 3 points at a time, draw a triangle, i.e. (V0, V1, v2), (v3, V4, v5) ...
(6) GL. Triangle_strip
Take the first 3 points to draw a triangle, and then take one point at a time, and draw a triangle with the two points in front, i.e. (V0, V1, v2), (v1, v2, v3) ...
(7) GL. Triangle_fan
Take the first 3 points to draw a triangle, and then take 1 points each time, with the last triangle row of the final edge of the triangle, namely (V0, V1, v2), (V0, V2, v3).
WebGL (5)--Polygon