webGL ——1

一回想,已经毕业两个月,来到中科软也快两个月了,业余时间学习webGL,个人感觉这个东西很有前途,分享给大家,也算是我的学习笔记吧!

下面把建立三角形和矩形的代码整理到这里:

/**

*初始化图形缓存区缓冲区实际上是图形卡上的内存

*/

functioninitBuffers(){

triangleVertexPositionBuffer=gl.createBuffer();//创建三角形顶点数组

gl.bindBuffer(gl.ARRAY_BUFFER,triangleVertexPositionBuffer);//绑定数值

varvertices=[

0.0,1.0,0.0,

-1.0,-1.0,0.0,

1.0,-1.0,0.0

];//定义三角形

gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array(vertices),gl.STATIC_DRAW);//vertices填充缓存区

triangleVertexPositionBuffer.itemSize=3;//缓存区的列

triangleVertexPositionBuffer.numItems=3;//缓存区的行三个独立的顶点位置(numItems),其中每一个由三个数(itemSize)组成

squareVertexPositionBuffer=gl.createBuffer();//正方形

gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer);

vertices=[

1.0,1.0,0.0,

-1.0,1.0,0.0,

1.0,-1.0,0.0,

-1.0,-1.0,0.0

];

gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array(vertices),gl.STATIC_DRAW);

squareVertexPositionBuffer.itemSize=3;

squareVertexPositionBuffer.numItems=4;

}

//将两个对象的顶点位置放置到图形卡上————————绘制图形

functiondrawScene(){

gl.viewport(0,0,gl.viewportWidth,gl.viewportHeight);//告诉WebGL画布的大小

gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);//清除画布

//mat4.perspective=function(a,b,c,d,e){a=c*Math.tan(a*Math.PI/360);b=a*b;returnmat4.frustum(-b,b,-a,a,c,d,e)};

mat4.perspective(45,gl.viewportWidth/gl.viewportHeight,0.1,100.0,pMatrix);//为场景设置透视参数

//mat3.identity=function(a){a[0]=1;a[1]=0;a[2]=0;a[3]=0;a[4]=1;a[5]=0;a[6]=0;a[7]=0;a[8]=1;returna};

mat4.identity(mvMatrix);//

mat4.translate(mvMatrix,[-1.5,0.0,-7.0]);//变换

gl.bindBuffer(gl.ARRAY_BUFFER,triangleVertexPositionBuffer);

gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute,triangleVertexPositionBuffer.itemSize,gl.FLOAT,false,0,0);

setMatrixUniforms();//把矩阵参数传到图形卡

gl.drawArrays(gl.TRIANGLES,0,triangleVertexPositionBuffer.numItems);//从顶点数组的第0项开始一直到第numItems个元素,将顶点数组绘制成三角形

//alert("triangleFinish!");

mat4.translate(mvMatrix,[3.0,0.0,0.0]);

gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer);

gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute,squareVertexPositionBuffer.itemSize,gl.FLOAT,false,0,0);

setMatrixUniforms();

gl.drawArrays(gl.TRIANGLE_STRIP,0,squareVertexPositionBuffer.numItems);

}

请大家主意:所有操作矩阵的函数都定义在mat4对象中!各位大侠多多指教!下一课再见!

相关推荐