书本源代码 https://download.csdn.net/download/qfire/10371055
2.1 绘制多个点
不管三维模型的形状多么复杂,其基本组成部分都是三角形,只不过复杂的模型由更多的三角形构成而已。
WebGL提供了一种很方便的机制,即缓冲区对象(buffer object),它可以一次性地向着色器传入多个顶点的数据。缓冲区对象使WebGL系统中的一块内存区域,我们可以一次性地向缓冲区对象中填充大量的顶点数据,然后将这些数据保存在其中,供顶点着色器使用。
//顶点着色器程序 var VSHADER_SOURCE = 'attribute vec4 a_Position;\n' + 'void main() {\n' + ' gl_Position = a_Position; \n' + //设置坐标 ' gl_PointSize = 10.0; \n' + //设置尺寸 '}\n'; //片元着色器程序 var FSHADER_SOURCE = 'void main() {\n' + ' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' + //设置颜色 '}\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; } // 初始化着色器 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; } //注册鼠标 //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); //清空 gl.clear(gl.COLOR_BUFFER_BIT); //绘制点 gl.drawArrays(gl.POINTS, 0, n); //点的位置和大小 } 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); //获取attribute变量的存储位置 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; }
五个步骤:
- 创建缓冲区对象(gl.createBuffer())
- 绑定缓冲区对象(gl.bindBuffer())
- 将数据写入缓冲区对象(gl.bufferData())
- 将缓冲区对象分配给一个attribute变量(gl.vertexAttribPointer())
- 开启attribute变量(gl.enableVertexAttribArray())
2.2 绘制三角形
gl.drawArrays(gl.TRIANGLES, 0, n);
2.3 移动、旋转和缩放
gl_Position.x = a_Position.x * u_CosB - a_Position.y * u_SinB;
变换矩阵:旋转3x3或4x4,平移4x4,