WebGl 一个缓冲区传递颜色和坐标(矩形)
效果:
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebGl 一个缓冲区传递颜色和坐标(矩形)</title> </head> <body> <canvas id="myCanvas" width="500" height="300" style='border:1px solid red'></canvas> </body> <script> window.onload = function () { //获取上下文 var canvas = document.getElementById('myCanvas'); var gl = canvas.getContext('webgl'); //定义矩形数据 并 将其储存在缓存对象 var vertices = [ -0.5,0.5,0.0, 0.0,0.0,1.0,//(x,y,z)(r,g,b)分别代表坐标和颜色 -0.5,-0.5,0.0, 1.0,0.0,0.0, 0.5,-0.5,0.0, 0.0,1.0,0.0, 0.5,0.5,0.0, 1.0,0.0,1.0, ]; var indices = [3,2,1,3,1,0]; 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);//注意 是 ELEMENT_ARRAY_BUFFER 不是 ARRAY_BUFFER gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); //bufferData 参数详解 //数据类型,可以是 gl.ARRAY_BUFFER , gl.ELEMENT_ARRAY_BUFFER //数据 //缓冲类型,有这么几种可以供我们选择 GL_STREAM_DRAW , GL_STATIC_DRAW ,GL_DYNAMIC_DRAW //缓冲区的数据偶尔变动用GL_STREAM_DRAW ,缓冲区的数据不变用GL_STATIC_DRAW,缓冲区数据经常变动用GL_DYNAMIC_DRAW //创建和编译着色器程序 var vertCode = 'attribute vec3 coordinates;'+ 'attribute vec3 color;'+ 'varying vec3 vColor;'+ 'void main(void) {' + ' gl_Position = vec4(coordinates, 1.0);' + 'vColor = color;'+ '}'; var fragCode = 'precision mediump float;'+ 'varying vec3 vColor;'+ 'void main(void) {'+ 'gl_FragColor = vec4(vColor, 1.0);'+ '}'; var vertShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader, vertCode); gl.compileShader(vertShader); var fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader, fragCode); gl.compileShader(fragShader); var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertShader); gl.attachShader(shaderProgram, fragShader); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); //与缓冲区对象相关联着色器程序 // vertices中每个元素的字节数 ,这里是 float 类型, 所以是 4 个字节 var bytes = new Float32Array(vertices).BYTES_PER_ELEMENT; var coord = gl.getAttribLocation(shaderProgram, "coordinates"); gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, bytes*6, 0); gl.enableVertexAttribArray(coord); var color = gl.getAttribLocation(shaderProgram, "color"); gl.vertexAttribPointer(color, 3, gl.FLOAT, false, bytes*6, bytes*3) ; gl.enableVertexAttribArray(color); //绘制所需的对象 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,canvas.width,canvas.height); gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0); } // vertexAttribPointer(location, int size, enum type, bool normalized, long stride, long offset) 参数详解 //Location − 它指定一个属性变量的存储位置。根据这个方案,必须通过由getAttribLocation()方法返回的值 //Size − 它指定在缓冲对象每顶点部件的数量 //Type − 它指定数据的类型 //Normalized − 这是一个布尔值。如果为真,非浮动数据被归一化到[0,1]。否则,它被归一化到[-1,1] //Stride − 它指定不同顶点数据元素之间的字节数,或默认为零步幅(字节) //Offset − 它指定在缓冲器对象,以指示数据从顶点的哪个存储字节偏移(字节) </script> </html>