# WebGL平移

## 轉換一個三角形步驟

`var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ];`

• 頂點著色器 - 在程式的頂點著色器，我們定義一個向量屬性來儲存三維坐標。除了它，我們定義儲存平移的距離一個統一變數，最後，我們新增這兩個值並將其分配給 gl_position 它儲存頂點的最終位置。
```var vertCode =
'attribute vec4 coordinates;' +
'uniform vec4 translation;'+
'void main(void) {' +
' gl_Position = coordinates + translation;' +
'}';```
• 片段著色器 - 在片段著色器，我們只分配片段顏色變 gl_FragColor。
`var fragCode = 'void main(void) {' +' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +'}';`

`gl.drawArrays(gl.TRIANGLES, 0, 3);`

## 範例 - 平移三角形

```<!doctype html>
<html>
<body>
<canvas width = "300" height = "300" id = "my_Canvas"></canvas>

<script>

/*=================Creating a canvas=========================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');

/*===========Defining and storing the geometry==============*/
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
];

//Create an empty buffer object and store vertex data
var vertex_buffer = gl.createBuffer();

//Create a new buffer
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);

//bind it to the current buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

// Pass the buffer data
gl.bindBuffer(gl.ARRAY_BUFFER, null);

var vertCode =
'attribute vec4 coordinates;' +
'uniform vec4 translation;'+
'void main(void) {' +
'  gl_Position = coordinates + translation;' +
'}';

//Create a vertex shader program object and compile it

var fragCode =
'void main(void) {' +
'   gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +
'}';

//Create a fragment shader program object and compile it

//Create and use combiened shader program

/* ===========Associating shaders to buffer objects============*/

gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.vertexAttribYiibaier(coordinatesVar, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(coordinatesVar);

/* ==========translation======================================*/
var Tx = 0.5, Ty = 0.5, Tz = 0.0;
gl.uniform4f(translation, Tx, Ty, Tz, 0.0);

/*=================Drawing the riangle and transforming it========================*/

gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.enable(gl.DEPTH_TEST);

gl.clear(gl.COLOR_BUFFER_BIT);
gl.viewport(0,0,canvas.width,canvas.height);
gl.drawArrays(gl.TRIANGLES, 0, 3);

</script>

</body>
</html>```