-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhello_world.html
executable file
·114 lines (96 loc) · 3.01 KB
/
hello_world.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebGL Hello world</title>
<style>
.buttons {
display: flex;
height: 30px;
align-items: center;
}
.buttons > button {
width: 40px;
}
.buttons .side {
width: 40px;
text-align: center;
}
</style>
</head>
<body>
<div class="buttons">
<div>边数: </div>
<button onclick="cal('-')">-</button>
<div class="side">3</div>
<button onclick="cal('+')">+</button>
</div>
<canvas width="300" height="300"></canvas>
<script>
let side = 3
function cal(type) {
eval(`side ${type}= 1`)
document.querySelector('.side').innerHTML = side
polygon.generatePolygon(side)
}
const vertex = `
attribute vec2 position;
varying vec3 color;
void main() {
gl_PointSize = 1.0;
color = vec3(0.5 + position * 0.5, 0.0);
gl_Position = vec4(position * 0.5, 1.0, 1.0);
}
`
const fragment = `
precision mediump float;
varying vec3 color;
void main()
{
gl_FragColor = vec4(color, 1.0);
}
`
class Polygon {
constructor(r = 1) {
this.r = r
const canvas = this.canvas = document.querySelector('canvas')
const gl = this.gl = canvas.getContext('webgl')
const vertexShader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vertexShader, vertex)
gl.compileShader(vertexShader)
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fragmentShader, fragment)
gl.compileShader(fragmentShader)
const program = this.program = gl.createProgram()
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
gl.linkProgram(program)
gl.useProgram(program)
this.generatePolygon(side, 2)
}
generatePolygon(n) {
const { gl, program, r } = this
const angle = (2 * Math.PI) / n
let points = []
for (let i = 0; i < n; i++) {
points.push(r * Math.cos(angle * i))
points.push(r * Math.sin(angle * i))
}
points = new Float32Array(points)
console.log(points)
const bufferId = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, bufferId)
gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW)
const vPosition = gl.getAttribLocation(program, 'position')
gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(vPosition)
gl.clear(gl.COLOR_BUFFER_BIT)
gl.drawArrays(gl.LINE_LOOP, 0, points.length / 2)
return points
}
}
const polygon = new Polygon(2)
</script>
</body>
</html>