1
在webgl中繪製了一個簡單的三角形之後,我決定開始學習如何進行轉換。所以基本上我在想,我能做的最簡單的事情就是寫一個單位矩陣並將其乘以頂點位置。第一步學習WEBGL中的學習矩陣
所以我添加到代碼的單位矩陣作爲
var identityMatrix = [1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1];
然後我加入到着色器中的MAT4變量
'uniform mat4 id_matrix;'
,再乘以它的位置(所以我預計根本沒有變化,因爲我把所有東西都乘以1)
gl_Position = id_matrix * vec4 (a_position,1);
Finall Ÿ我在着色器檢索矩陣的位置,並與我的數據
var shaderIdentityMatrix = gl.getUniformLocation(program, "id_matrix");
gl.uniformMatrix4fv(shaderIdentityMatrix,false,new Float32Array(identityMatrix));
但這些更改後填充它,沒有出現在屏幕上。我在做錯誤的假設嗎?
下面是完整的代碼
<!DOCTYPE HTML>
<html>
<canvas id = "can" width="400" height="400">
</canvas>
<script>
var webgl_canvas = document.getElementById('can');
var gl = webgl_canvas.getContext('experimental-webgl');
var triangles = [-0.8,-0.8,0,0.8,-0.8,0,0,0.8,0];
var identityMatrix = [1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1];
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(triangles), gl.STATIC_DRAW);
vertexBuffer.itemSize = 3;
vertexBuffer.numItems = 3;
var vertexShader_source = 'attribute vec3 a_position;' + 'uniform mat4 id_matrix;' + 'void main() { gl_Position = id_matrix * vec4 (a_position,1); }';
var fragmentShader_source = 'precision mediump float;' + 'void main() { gl_FragColor = vec4 (0.9,0,0.1,1); }';
//Compile shaders
var buildShader = function (shaderSource, typeOfShader) {
var shader = gl.createShader(typeOfShader);
gl.shaderSource(shader, shaderSource);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert (gl.getShaderInfoLog(shader));
}
return shader;
}
var compiledVertexShader = buildShader (vertexShader_source, gl.VERTEX_SHADER);
var compiledFragmentShader = buildShader (fragmentShader_source, gl.FRAGMENT_SHADER);
//setup GLSL program
program = gl.createProgram();
gl.attachShader(program,compiledVertexShader);
gl.attachShader(program,compiledFragmentShader);
gl.linkProgram(program);
//Draw
var shaderIdentityMatrix = gl.getUniformLocation(program, "id_matrix");
gl.uniformMatrix4fv(shaderIdentityMatrix,false,new Float32Array(identityMatrix));
var positionLocation = gl.getAttribLocation(program,"a_position");
gl.enableVertexAttribArray(positionLocation);
gl.useProgram(program);
gl.vertexAttribPointer(positionLocation, vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.drawArrays (gl.TRIANGLES, 0, vertexBuffer.numItems);
</script>
</html>
奇怪,因爲即使在程序被調用之前,getAttribLocation也能正常工作。 – 2014-10-28 12:39:53
那是正確的。但是當你看到這些函數時,你會注意到你必須在getAttribLocation中輸入程序ID,而不是在uniformMatrix4fv中輸入。 :) – BDL 2014-10-28 13:54:27