效果: 代碼: ...
效果:
代碼:
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>