在这里,我们把几何对象的变换用矩阵变换的形式给出,方便大家理解。
1.平移操作。
2.二维旋转,假设绕原点旋转θ度。
3.1三维旋转,绕X轴旋转,X坐标不变。
3.2三维旋转,绕Y轴旋转,Y坐标不变。
4.缩放,原点不动,沿坐标轴伸缩。
5.绕Y轴旋转角计算。
6.这里给出正方形旋转的示例,js文件全部代码:
var gl;
var theta = 0.0;
var thetaLoc;
var speed = 100;
var direction = true;
window.onload = function init()
{
var canvas = document.getElementById( "gl-canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
// Load shaders and initialize attribute buffers
var program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
var vertices = [
vec2( 0, 1 ),
vec2( -1, 0 ),
vec2( 1, 0 ),
vec2( 0, -1 )
];
// Load the data into the GPU
var bufferId = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, bufferId);
gl.bufferData(gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW);
// Associate out shader variables with our data buffer
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray(vPosition);
thetaLoc = gl.getUniformLocation(program, "theta");
// Initialize event handlers
document.getElementById("slider").onchange = function(event) {
speed = 100 - event.target.value;
};
document.getElementById("Direction").onclick = function (event) {
direction = !direction;
};
document.getElementById("Controls").onclick = function( event) {
switch(event.target.index) {
case 0:
direction = !direction;
break;
case 1:
speed /= 2.0;
break;
case 2:
speed *= 2.0;
break;
}
};
window.onkeydown = function( event ) {
var key = String.fromCharCode(event.keyCode);
switch( key ) {
case '1':
direction = !direction;
break;
case '2':
speed /= 2.0;
break;
case '3':
speed *= 2.0;
break;
}
};
render();
};
function render()
{
gl.clear( gl.COLOR_BUFFER_BIT );
theta += (direction ? 0.1 : -0.1);
gl.uniform1f(thetaLoc, theta);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
setTimeout(
function () {requestAnimFrame( render );},
speed
);
}
html文件中“关键”代码:
<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec4 vPosition;
uniform float theta;
void
main()
{
float s = sin( theta );
float c = cos( theta );
gl_Position.x = -s * vPosition.y + c * vPosition.x;
gl_Position.y = s * vPosition.x + c * vPosition.y;
gl_Position.z = 0.0;
gl_Position.w = 1.0;
}
</script>
<script id="fragment-shader" type="x-shader/x-fragment">
precision mediump float;
void
main()
{
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}
</script>