旋转矩阵示例,学习时例子太复杂精简了一个出来
const canvas = document.querySelector('canvas');
const gl = canvas.getContext('webgl');
const vertex = `
attribute vec2 position;
uniform float u_rotation;
void main() {
float rad = u_rotation ;
mat3 rotateMatrix = mat3(
cos(rad), sin(rad), 0.0,
-sin(rad), cos(rad), 0.0,
0.0, 0.0, 1.0
);
gl_PointSize = 1.0;
vec3 pos = rotateMatrix * vec3(position, 1.0);
gl_Position = vec4(pos, 1.0);
}
`;
const fragment = `
precision mediump float;
void main()
{
gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0);
}
`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertex);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragment);
gl.compileShader(fragmentShader);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);
const position = new Float32Array([
-1.732/2, -0.5,
0, 1,
1.732/2, -0.5,
]);
const bufferId = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, bufferId);
gl.bufferData(gl.ARRAY_BUFFER, position, gl.STATIC_DRAW);
const vPosition = gl.getAttribLocation(program, 'position');
gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vPosition);
function setUniforms(gl, u_rotation) {
let loc = gl.getUniformLocation(program, 'u_rotation');
gl.uniform1f(loc, u_rotation);
}
let startTime=performance.now();
function update(t) {
gl.clear(gl.COLOR_BUFFER_BIT);
let u_rotation = ((performance.now() - startTime) %16000)/16000.0*Math.PI*2;
setUniforms(gl, u_rotation);
gl.drawArrays(gl.TRIANGLES, 0, position.length / 2);
requestAnimationFrame(update);
}
requestAnimationFrame(update);