-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathColoredTriangle.html
More file actions
86 lines (75 loc) · 2.59 KB
/
ColoredTriangle.html
File metadata and controls
86 lines (75 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style>
#box {
background-color: pink;
}
#pic {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="box">
<canvas id="pic" width="500px" height="500px">
</div>
</body>
<script src="lib/cuon-matrix.js"></script>
<script src="lib/webgl-utils.js"></script>
<script src="lib/webgl-debug.js"></script>
<script src="lib/cuon-utils.js"></script>
<script>
window.onload = (function() {
var VSHADER_SOURCE = `
attribute vec4 a_Position;
attribute vec4 a_Color;
varying vec4 v_Color;
void main(){gl_Position = a_Position;gl_PointSize = 10.0;v_Color = a_Color;}
`;
var FSHADER_SOURCE = `
precision mediump float;
varying vec4 v_Color;
void main(){gl_FragColor = v_Color;}
`;
var canvas = document.getElementById("pic");
// ======================================================================
var gl = getWebGLContext(canvas);
//初始化着色器
initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE);
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
var n = initVertexBuffers(gl);
//设置画布底色
gl.clearColor(0.0, 0.0, 0.0, 1.0);
//清除颜色缓冲区
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, n);
function initVertexBuffers(gl) {
var n = 3;
var verticesColors = new Float32Array([
0.0, 0.5, 1.0, 0.0, 0.0,
-0.5, -0.5, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0,
]);
//创建了缓冲区对象
var vertexColorBuffer = gl.createBuffer();
//将缓冲区对象绑定到目标
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
//向缓冲区对象写入数据
gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW);
var FSIZE = verticesColors.BYTES_PER_ELEMENT;
//将缓冲区对象分配给a_Position变量
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE * 5, 0);
gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 5, FSIZE * 2);
//连接a_Position变量与分配给它的缓冲区对象
gl.enableVertexAttribArray(a_Position);
gl.enableVertexAttribArray(a_Color);
return n;
}
});
</script>
</html>