效果:
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebGl 利用drawArrays、drawElements画三角形</title> </head> <body> <canvas id="myCanvas" width="500" height="300" style="border: 1px solid red"></canvas> </body> <script> window.onload = function () { //第1步 - 准备Canvas和获取WebGL的渲染上下文 var canvas = document.getElementById('myCanvas'), gl = canvas.getContext('webgl'); //第2步 - 定义几何并将其存储在缓冲区对象 var vertices = [ -0.5,0.5,0.0, 0.0,0.5,0.0, -0.25,0.25,0.0, 0.5,0.5,0.0, 0.25,0.25,0.0, ], indices =[0,1,2,1,3,4]; var vertex_buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER,vertex_buffer); gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertices),gl.STATIC_DRAW); var Index_Buffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); //第3步 - 创建和编译着色器程序 var vertCode = 'attribute vec3 coordinates;' + 'void main(void) {' + ' gl_Position = vec4(coordinates, 1.0);' + '}'; var fragCode = 'void main(void) {' + ' gl_FragColor = vec4(1, 0.5, 0.0, 1);' + '}'; var vertShader = gl.createShader(gl.VERTEX_SHADER); var fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(vertShader,vertCode); gl.shaderSource(fragShader,fragCode); gl.compileShader(vertShader); gl.compileShader(fragShader); var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram,vertShader); gl.attachShader(shaderProgram,fragShader); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); //第4步 - 关联着色器程序到缓冲区对象 var coord = gl.getAttribLocation(shaderProgram,'coordinates'); gl.vertexAttribPointer(coord,3,gl.FLOAT,false,0,0); gl.enableVertexAttribArray(coord); //第5步 - 绘制所需的对象 gl.clearColor(0.5, 0.5, 0.5, 0.9); gl.enable(gl.DEPTH_TEST); gl.clear(gl.COLOR_BUFFER_BIT); gl.viewport(0,0,myCanvas.width,myCanvas.height); //gl.drawArrays(gl.TRIANGLES, 0, 3)//画简单的三角形 此方法不需要索引 //gl.drawArrays(gl.TRIANGLES, 0, 6)//如果下需要画两个三角形 那么vertices数组中需要增加一个点 gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);//利用drawElements画三角形 //画矩形 更改indices即可 //绘图模式如下: //gl.POINTS:要绘制一系列的点 //gl.LINES:要绘制了一系列未连接直线段(单独行) //gl.LINE_STRIP:要绘制一系列连接的线段 //gl.LINE_LOOP:要绘制一系列连接的线段。它还连接的第一和最后的顶点,以形成一个环 //TRIANGLES:一系列单独的三角形;绘制方式:(v0,v1,v2),(v1,v3,v4) //TRIANGLE_STRIP:一系列带状的三角形 //TRIANGLE_FAN:扇形绘制方式 } </script> </html>