Book source code https://download.csdn.net/download/qfire/10371055
2.1 Drawing multiple points
No matter how complex the shape of a 3D model, its basic components are triangles, but complex models are made up of more triangles.
WebGL provides a convenient mechanism, the buffer object, which can pass data for multiple vertices to the shader at once. The buffer object is a memory area in the WebGL system. We can fill a large amount of vertex data into the buffer object at one time, and then save this data in it for use by the vertex shader.
// vertex shader program var VSHADER_SOURCE = 'attribute vec4 a_Position;\n' + 'void main() {\n' + ' gl_Position = a_Position; \n' + //set coordinates ' gl_PointSize = 10.0; \n' + //set size '}\n'; // fragment shader program var FSHADER_SOURCE = 'void main() {\n' + ' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' + //set color '}\n'; function main() { var canvas = document.getElementById('webgl'); var gl = getWebGLContext(canvas); if (!gl) { console.log("Failed to get the rendering context for WebGL"); return; } // initialize shader if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) { console.log('Failed to initialize shaders.'); return ; } // var n = initVertexBuffers (gl); if (n < 0) { console.log("Failed to set the positions of the vertices"); return; } // register the mouse //canvas.onmousedown = function(ev) { click(ev, gl, canvas, a_Position, u_FragColor)}; //gl.vertexAttrib3f(a_Position, 0.0, 0.0, 0.0); // RGBA gl.clearColor(0.0, 0.0, 0.0, 1.0); // clear gl.clear(gl.COLOR_BUFFER_BIT); // draw points gl.drawArrays(gl.POINTS, 0, n); //Position and size of points } function initVertexBuffers(gl) { var vertices = new Float32Array([ 0.0, 0.5, -0.5, -0.5, 0.5, -0.5 ]); var n = 3; var vertexBuffer = gl.createBuffer(); if (!vertexBuffer) { console.log("Failed to create the buffer object"); return -1; } // gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); // Write data into the buffer object gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); //Get the storage location of the attribute variable var a_Position = gl.getAttribLocation(gl.program, 'a_Position'); if (a_Position < 0) { console.log("failed to get the storage location of a_Position"); return; } // gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0); // gl.enableVertexAttribArray(a_Position); return n; }
Five steps :
- Create a buffer object (gl.createBuffer())
- Bind buffer object (gl.bindBuffer())
- Write data to a buffer object (gl.bufferData())
- Assign the buffer object to an attribute variable (gl.vertexAttribPointer())
- Enable attribute variables (gl.enableVertexAttribArray())
2.2 Drawing triangles
gl.drawArrays(gl.TRIANGLES, 0, n);
2.3 Move, rotate and zoom
gl_Position.x = a_Position.x * u_CosB - a_Position.y * u_SinB;
Transformation matrix : rotate 3x3 or 4x4, translate 4x4,