效果:
代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>WebGl 多缓冲区传递颜色和坐标(矩形)</title> 6 </head> 7 <body> 8 9 <canvas id="myCanvas" width="500" height="300" style='border:1px solid red'></canvas> 10 11 </body> 12 13 <script> 14 15 window.onload = function () { 16 17 //获取上下文 18 var canvas = document.getElementById('myCanvas'); 19 var gl = canvas.getContext('webgl'); 20 21 //定义矩形数据 并 将其储存在缓存对象 22 var vertices = [ 23 -0.5,0.5,0.0, 24 -0.5,-0.5,0.0, 25 0.5,-0.5,0.0, 26 0.5,0.5,0.0 27 ]; 28 var colors = [ 29 0,0,1, 30 1,0,0, 31 0,1,0, 32 1,0,1, 33 ]; 34 var indices = [3,2,1,3,1,0]; 35 36 var vertex_buffer = gl.createBuffer(); 37 gl.bindBuffer(gl.ARRAY_BUFFER,vertex_buffer); 38 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); 39 40 var Index_Buffer = gl.createBuffer(); 41 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,Index_Buffer);//注意 是 ELEMENT_ARRAY_BUFFER 不是 ARRAY_BUFFER 42 gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); 43 44 var color_buffer = gl.createBuffer (); 45 gl.bindBuffer(gl.ARRAY_BUFFER,color_buffer); 46 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); 47 48 //创建和编译着色器程序 49 var vertCode = 'attribute vec3 coordinates;'+ 50 'attribute vec3 color;'+ 51 'varying vec3 vColor;'+ 52 53 'void main(void) {' + 54 ' gl_Position = vec4(coordinates, 1.0);' + 55 'vColor = color;'+ 56 '}'; 57 var fragCode = 'precision mediump float;'+ 58 'varying vec3 vColor;'+ 59 'void main(void) {'+ 60 'gl_FragColor = vec4(vColor, 1.0);'+ 61 '}'; 62 63 var vertShader = gl.createShader(gl.VERTEX_SHADER); 64 gl.shaderSource(vertShader, vertCode); 65 gl.compileShader(vertShader); 66 67 var fragShader = gl.createShader(gl.FRAGMENT_SHADER); 68 gl.shaderSource(fragShader, fragCode); 69 gl.compileShader(fragShader); 70 71 var shaderProgram = gl.createProgram(); 72 gl.attachShader(shaderProgram, vertShader); 73 gl.attachShader(shaderProgram, fragShader); 74 gl.linkProgram(shaderProgram); 75 gl.useProgram(shaderProgram); 76 77 78 //与缓冲区对象相关联着色器程序 79 gl.bindBuffer(gl.ARRAY_BUFFER,vertex_buffer);//这里要注意的是 现在存在多个缓冲区 取属性值得时候 一定先告诉从哪个缓冲区取值 否则默认是最后一个bindBuffer()指定的; 80 var coord = gl.getAttribLocation(shaderProgram, "coordinates"); 81 gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0); 82 gl.enableVertexAttribArray(coord); 83 84 gl.bindBuffer(gl.ARRAY_BUFFER,color_buffer);//这里要注意的是 现在存在多个缓冲区 取属性值得时候 一定先告诉从哪个缓冲区取值 否则默认是最后一个bindBuffer()指定的; 85 var color = gl.getAttribLocation(shaderProgram, "color"); 86 gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ; 87 gl.enableVertexAttribArray(color); 88 89 90 //绘制所需的对象 91 gl.clearColor(0.5, 0.5, 0.5, 0.9); 92 gl.enable(gl.DEPTH_TEST); 93 gl.clear(gl.COLOR_BUFFER_BIT); 94 gl.viewport(0,0,canvas.width,canvas.height); 95 gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0); 96 97 } 98 99 </script> 100 101 </html>