-
Notifications
You must be signed in to change notification settings - Fork 108
/
lesson4.html
97 lines (87 loc) · 2.96 KB
/
lesson4.html
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
87
88
89
90
91
92
93
94
95
96
97
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>单个 buffer 绘制渐变三角形</title>
<link rel = "stylesheet" href="../css/common.css" />
</head>
<body>
<canvas id="canvas"></canvas>
<script type="shader-source" id="vertexShader">
//浮点数设置为中等精度
precision mediump float;
//接收 JavaScript 传递过来的点的坐标(X, Y)
attribute vec2 a_Position;
// 接收canvas的尺寸。
attribute vec2 a_Screen_Size;
attribute vec4 a_Color;
varying vec4 v_Color;
void main(){
// 将 canvas 的坐标值 转换为 [-1.0, 1.0]的范围。
vec2 position = (a_Position / a_Screen_Size) * 2.0 - 1.0;
// canvas的 Y 轴坐标方向和 设备坐标系的相反。
position = position * vec2(1.0, -1.0);
// 最终的顶点坐标。
gl_Position = vec4(position, 0.0, 1.0);
v_Color = a_Color;
}
</script>
<script type="shader-source" id="fragmentShader">
//浮点数设置为中等精度
precision mediump float;
// 用来接收顶点着色器插值后的颜色。
varying vec4 v_Color;
void main(){
// 将颜色处理成 GLSL 允许的范围[0, 1]。
vec4 color = v_Color / vec4(255, 255, 255, 1);
// 点的最终颜色。
gl_FragColor = color;
}
</script>
<script src="../utils/webgl-helper.js"></script>
<script>
//获取canvas
let canvas = getCanvas('#canvas');
//设置canvas尺寸为满屏
resizeCanvas(canvas);
//获取绘图上下文
let gl = getContext(canvas);
//创建着色器程序
let program = createSimpleProgramFromScript(gl, 'vertexShader', 'fragmentShader');
//使用该着色器程序
gl.useProgram(program);
let a_Screen_Size = gl.getAttribLocation(program, 'a_Screen_Size');
gl.vertexAttrib2f(a_Screen_Size, canvas.width, canvas.height);
let positions = [];
let a_Position = gl.getAttribLocation(program, 'a_Position');
let a_Color = gl.getAttribLocation(program, 'a_Color');
gl.enableVertexAttribArray(a_Position);
gl.enableVertexAttribArray(a_Color);
let buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 24, 0);
gl.vertexAttribPointer(a_Color, 4, gl.FLOAT, false, 24, 8);
//设置清屏颜色为黑色。
gl.clearColor(0, 0, 0, 1);
canvas.addEventListener("click", e=>{
positions.push(e.pageX, e.pageY);
let color = randomColor();
positions.push(color.r, color.g, color.b, color.a);
// 顶点信息为 18 的整数倍即3个顶点时执行绘制操作,因为三角形由三个顶点组成,每个顶点由六个元素组成。
if(positions.length % 18 == 0) {
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
render(gl);
}
})
function render(gl){
gl.clear(gl.COLOR_BUFFER_BIT);
let primitiveType = gl.TRIANGLES;
if(positions.length > 0){
gl.drawArrays(primitiveType, 0, positions.length / 6);
}
}
render(gl);
</script>
</body>
</html>