webgl复习笔记——[回顾]从零绘制三角形
单词容易拼写错误。记得排查。
let canvas = document.getElementById('webgl');
let gl = canvas.getContext('webgl');
let v_shader = `
attribute vec4 v_position;
void main(){
gl_Position = v_position;
}
`;
let f_shader = `
void main(){
gl_FragColor = vec4(1.0,0,0,1);
}
`;
initProgram();
function initProgram() {
let vshader = gl.createShader(gl.VERTEX_SHADER);
let fshader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(vshader,v_shader);
gl.shaderSource(fshader,f_shader);
gl.compileShader(vshader);
gl.compileShader(fshader);
let program = gl.createProgram();
gl.attachShader(program,vshader);
gl.attachShader(program,fshader);
gl.linkProgram(program);
gl.useProgram(program);
gl.program = program;
};
let n = initBuffer();
function initBuffer(){
let points = new Float32Array([
0,.5,
.5,-.5,
-.5,-.5
]);
let buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER,points,gl.STATIC_DRAW);
let a_position = gl.getAttribLocation(gl.program, 'v_position');
gl.vertexAttribPointer(a_position,2,gl.FLOAT,false,0,0);
gl.enableVertexAttribArray(a_position);
return points.length / 2;
}
gl.clearColor(0,0,0,1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, n);