DAY 7
0
Modern Web

# [Day7] webGL修羅道 - 3D 與動畫

## 3D 圖形基礎

``````var vertices = [
-1, -1, -1,     1, 0, 0, 1,     // 0
1, -1, -1,     1, 1, 0, 1,     // 1
-1,  1, -1,     0, 1, 1, 1,     // 2
1,  1, -1,     0, 0, 1, 1,     // 3
-1,  1,  1,     1, 0.5, 0, 1,   // 4
1,  1,  1,     0.5, 1, 1, 1,   // 5
-1, -1,  1,     1, 0, 0.5, 1,   // 6
1, -1,  1,     0.5, 0, 1, 1,   // 7
];

``````

### 用 gl.drawElements 取代 gl.drawArrays 畫出

``````function createIndices() {
// 建立索引，讓 webGL 知道要取用哪些頂點
var indices = [
0, 1, 2,   1, 2, 3,
2, 3, 4,   3, 4, 5,
4, 5, 6,   5, 6, 7,
6, 7, 0,   7, 0, 1,
0, 2, 6,   2, 6, 4,
1, 3, 7,   3, 7, 5
];
indexCount = indices.length;

var indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array(indices), gl.STATIC_DRAW);
}
``````

``````// 原本為 gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
// 第五個參數代表每次取用頂點後，下一次的頂點從哪裡開始 Float32Array.BYTES_PER_ELEMENT * 7
gl.vertexAttribPointer(coords, 3, gl.FLOAT, false, Float32Array.BYTES_PER_ELEMENT * 7, 0);
gl.enableVertexAttribArray(coords);
``````

### 建立動畫

``````<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.3.2/gl-matrix-min.js"></script>
``````

#### 將 perspective matrix 及 transform matrix 加入 shader

``````uniform mat4 u_transformMatrix;
uniform mat4 u_perspectiveMatrix;

void main(void) {
gl_Position = perspectiveMatrix * transformMatrix  * coords;
gl_PointSize = pointSize;
varyingColors = colors;
}
``````

``````mat4.rotateX(matrix, matrix, -0.043); // 每次旋轉 X -0.043
mat4.rotateY(matrix, matrix, 0.01); // 每次旋轉 0.01
mat4.rotateZ(matrix, matrix, 0.01); // 每次旋轉 0.01

var transformMatrix = gl.getUniformLocation(shaderProgram, "transformMatrix");
gl.uniformMatrix4fv(transformMatrix, false, matrix);
``````

webGL cube animation