WebGL 旋转的三角形

旋转矩阵示例,学习时例子太复杂精简了一个出来

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值