绘制不同颜色

绘制过程

  1. 执行 Vertex Shader,配置顶点。
  2. 调用gl.drawArrays(),装配图形。
  3. 光栅化,将图形转换为 Fragment。
  4. 执行 Fragment Shader。

代码实现

使用varying标识符

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
const vShaderSource = `
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;
}
`

const fShaderSource = `
precision mediump float;
varying vec4 v_Color;
void main() {
gl_FragColor = v_Color;
}
`

const main = () => {
const gl = document.querySelector("#canvas").getContext("webgl")
if (!initShaders(gl, vShaderSource, fShaderSource)) return

let n = initVertexBuffers(gl)
if (n < 0) return

gl.clearColor(0, 0, 0, 1)
gl.clear(gl.COLOR_BUFFER_BIT)

// gl.drawArrays(gl.LINE_LOOP, 0, n);
gl.drawArrays(gl.TRIANGLES, 0, n)
}

const initVertexBuffers = (gl) => {
let verticesColor = new Float32Array([
// [x, y, r, g, b]
0, 0.5, 1, 0, 0, -0.5, -0.5, 0, 1, 0, 0.5, -0.5, 0, 0, 1,
])
let n = 3

let vertexColorBuffer = gl.createBuffer()
if (!vertexColorBuffer) return -1
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer)
gl.bufferData(gl.ARRAY_BUFFER, verticesColor, gl.STATIC_DRAW)

const SIZE = verticesColor.BYTES_PER_ELEMENT
let a_Position = gl.getAttribLocation(gl.program, "a_Position")
let a_Color = gl.getAttribLocation(gl.program, "a_Color")

gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, SIZE * 5, 0)
gl.enableVertexAttribArray(a_Position)

gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, SIZE * 5, SIZE * 2)
gl.enableVertexAttribArray(a_Color)

return n
}