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>

 

转载于:https://www.cnblogs.com/zhinian-/p/10631463.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值