//案例3.绘制三角形,将顶点数据存到缓冲区对象(gl.ARRAY_BUFFER)中,然后顶点着色器从里面读数据(3个顶点) //顶点着色器中去掉gl_PointSize = 10.0,绘制三角不能设置顶点的大小 //gl.drawArrays(gl.TRIANGLES,0,n);第一个参数改为三角,因为此时不是绘制点了 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.TRIANGLES,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; } //将缓冲区对象绑定到目标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();
其实,绘制三角形和之前的绘制三个点的代码很相似,只是:
在顶点着色器里面,我们不能设置点的size了(gl_PointSize);
绘图函数将从gl.drawArrays(gl.POINTS,0,n)变成gl.drawArrays(gl.TRIANGLES,0,n);
效果如下:
原文:https://www.cnblogs.com/eco-just/p/10673736.html