图像旋转

旋转原理

将 WebGL 坐标系转为极坐标,然后通过角度计算得出旋转后的左标位置。
旋转矩阵:

$$
\begin{bmatrix}
x’ \
y’ \
z’ \
1 \
\end{bmatrix} =
\begin{bmatrix}
\cos \beta & -\sin \beta & 0 & 0 \
\sin \beta & \cos \beta & 0 & 0 \
0 & 0 & 1 & 0 \
0 & 0 & 0 & 1 \
\end{bmatrix} ×
\begin{bmatrix}
x \
y \
z \
1 \
\end{bmatrix}
$$

代码实现

使用u_SinBCosB存放SinBCosB

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
/**
* 2d rotate
* x' = x * cosB - y * sinB
* y' = x * sinB + y * cosB
* z' = z
*/
const vShaderSource = `
attribute vec4 a_Position;
uniform vec2 u_SinBCosB;
void main() {
gl_Position.x = a_Position.x * u_SinBCosB.y - a_Position.y * u_SinBCosB.x;
gl_Position.y = a_Position.x * u_SinBCosB.x + a_Position.y * u_SinBCosB.y;
gl_Position.z = a_Position.z;
gl_Position.w = 1.0;
}
`

const fShaderSource = `
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`

let ANGLE = 30.0

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

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

let radian = (Math.PI * ANGLE) / 180.0 // Transform to radian.
let SinB = Math.sin(radian)
let CosB = Math.cos(radian)

let u_SinBCosB = gl.getUniformLocation(gl.program, "u_SinBCosB")

gl.uniform2f(u_SinBCosB, SinB, CosB)

gl.clearColor(0.0, 0.0, 0.0, 1.0)
gl.clear(gl.COLOR_BUFFER_BIT)

gl.drawArrays(gl.TRIANGLES, 0, n)
}