//案例4,绘制矩形,和三角形类似,但是注意因为一个矩形有4个顶点,按照两个三角形绘制矩形的话,顶点顺序要注意 var vShader = ` attribute vec4 a_Position; void main(){ gl_Position = a_Position; } `; var fShader = ` void main(){ gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); } `; function main(){ //获取canvas元素 var canvas = document.getElementById('webgl'); //获取webgl上下文 var gl = getWebGLContext(canvas); if(!gl){ console.log('Failed to get the rendering context for WebGL!'); return; } //初始化着色器 if(!initShaders(gl,vShader,fShader)){ 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; } //用指定颜色填充webgl容器,就是设置背景 gl.clearColor(0.4, 0.5, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLE_STRIP,0,n); function initVertexBuffers(gl){
//四个顶点 var vertices = new Float32Array([ -0.5,0.5,-0.5,-0.5,0.5,0.5,0.5,-0.5 ]); var n = 4;//点的个数 //创建缓冲区对象 var vertexBuffer = gl.createBuffer(); if(!vertexBuffer){ console.log('Failed to create the buffer object!'); return -1; } //将缓冲区对象绑定到目标ARRAY_BUFFER gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer); //往ARRAY_BUFFER gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW); //获取shaderProgram中attribute变量‘a_Position’的地址 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 -1; } //将缓冲区对象分配给a_Position变量 gl.vertexAttribPointer(a_Position,2,gl.FLOAT,false,0,0); //开启着色器对缓冲区数据的访问 gl.enableVertexAttribArray(a_Position); return n; } } main();
红字地方是相较绘制三角形作更改的。
另外,4个顶点的顺序,如下所示,有讲究的:
所以点坐标顺序为p1、p2、p3、p4.
其他绘制API(你可以根据如下API绘制你想要的图形):