这一节主要讲一下WebGL的基本变换,平移和旋转,主要运用了cuon-matrix.js库函数,其具体方法有以下:
下面讲解一个简单的例子,这个例子实现一个三角形先进行一次平移,在进行一次旋转,先看代码:
// TranslatedRotatedTriangle.js (c) 2012 matsuda
// Vertex shader program
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'uniform mat4 u_ModelMatrix;\n' +
'void main() {\n' +
' gl_Position = u_ModelMatrix * a_Position;\n' +
'}\n';
// Fragment shader program
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
'}\n';
function main() {
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to intialize shaders.');
return;
}
// Write the positions of vertices to a vertex shader
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}
// Create Matrix4 object for model transformation
var modelMatrix = new Matrix4();
// Calculate a model matrix
var ANGLE = 60.0; // 旋转角
var Tx = 0.5; // 平移距离
modelMatrix.setTranslate(Tx, 0, 0); // 平移
modelMatrix.rotate(ANGLE, 0, 0, 1); // 旋转
//将模型矩阵传输给顶点着色器
var u_ModelMatrix = gl.getUniformLocation(gl.program, 'u_ModelMatrix');
if (!u_ModelMatrix) {
console.log('Failed to get the storage location of u_xformMatrix');
return;
}
gl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements);
// Specify the color for clearing <canvas>
gl.clearColor(0, 0, 0, 1);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw the rectangle
gl.drawArrays(gl.TRIANGLES, 0, n);
}
function initVertexBuffers(gl) {
var vertices = new Float32Array([
0, 0.3, -0.3, -0.3, 0.3, -0.3
]);
var n = 3; // The number of vertices
// Create a buffer object
var vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.log('Failed to create the buffer object');
return false;
}
// Bind the buffer object to target
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
// Write date into the buffer object
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return -1;
}
// Assign the buffer object to a_Position variable
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
// Enable the assignment to a_Position variable
gl.enableVertexAttribArray(a_Position);
return n;
}
程序中先使用modelMatrix.setTranslate(Tx, 0, 0)将modelMatrix设置成平移矩阵,然后使用modelMatrix.rotate(ANGLE, 0, 0, 1)绕Z轴旋转ANGLE角度,计算出来的矩阵放入到modelMatrix中,然后使用gl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements)传递给模型着色器中的变量,最后显示出来效果如下: