WebGl 画线
效果:
代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>WebGl 画线</title> 6 </head> 7 <body> 8 <canvas id="myCanvas" width="500" height="300" style='border:1px solid red'></canvas> 9 </body> 10 11 <script> 12 13 window.onload = function () { 14 15 //获取上下文 16 var canvas = document.getElementById('myCanvas'); 17 var gl = canvas.getContext('webgl'); 18 19 //定义线段数组 20 var vertices = [ 21 -0.7,-0.1,0, 22 -0.3,0.6,0, 23 -0.3,-0.3,0, 24 0.2,0.6,0, 25 0.3,-0.3,0, 26 0.7,0.6,0 27 ] 28 29 var vertex_buffer = gl.createBuffer(); 30 gl.bindBuffer(gl.ARRAY_BUFFER,vertex_buffer); 31 gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertices), gl.STATIC_DRAW); 32 33 //着色器程序 34 var vertCode = 35 "attribute vec3 coordinates;" + 36 "void main() {" + 37 "gl_Position = vec4(coordinates,1.0);" + //位置 38 "}"; 39 var fragCode = 40 "void main() {" + 41 "gl_FragColor = vec4(1, 0.5, 0.0, 1);" + //RBGA值 42 "}"; 43 44 var vertShader = gl.createShader(gl.VERTEX_SHADER); 45 var fragShader = gl.createShader(gl.FRAGMENT_SHADER); 46 gl.shaderSource(vertShader,vertCode); 47 gl.shaderSource(fragShader,fragCode); 48 gl.compileShader(vertShader); 49 gl.compileShader(fragShader); 50 51 var shaderProgram = gl.createProgram(); 52 gl.attachShader(shaderProgram,vertShader); 53 gl.attachShader(shaderProgram,fragShader); 54 gl.linkProgram(shaderProgram); 55 gl.useProgram(shaderProgram); 56 57 //关联着色器程序到缓冲对象 58 var coord = gl.getAttribLocation(shaderProgram,'coordinates'); 59 gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0); 60 gl.enableVertexAttribArray(coord); 61 62 //画线 63 gl.clearColor(0.5, 0.5, 0.5, 0.9); 64 gl.enable(gl.DEPTH_TEST); 65 gl.clear(gl.COLOR_BUFFER_BIT); 66 gl.viewport(0,0,myCanvas.width,myCanvas.height); 67 gl.drawArrays(gl.LINES, 0, 6); 68 69 70 } 71 72 </script> 73 74 </html>