下面将从一个画一个三角形来介绍webgl程序的流程,大致执行流程如下图所示:
下面从上图的WebGL的大致流程实现如何画一个三角形:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webgl第一课——画一个三角形</title>
<style>
html,body {
padding: 0;
margin: 0;
}
canvas{
margin: 50px;
}
</style>
</head>
<body>
<canvas height="800px" width="800px" id="canvas"></canvas>
<script>
// 第一步 获取canvas对象
const canvas = document.getElementById('canvas');
// 第二步 获取WebGL上下文
const gl = canvas.getContext('webgl');
//第三步 初始化着色器
// 3.1 初始化顶点着色器
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
const vertexShaderSource = `
attribute vec4 a_Position;
void main(){
gl_Position = a_Position;
}
`;
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);
if(!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)){
console.log(gl.getShaderInfoLog(vertexShader));
}
//3.2 初始化片元着色器
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
const fragmentShaderSource = `
void main(){
gl_FragColor = vec4(1.0,0.0,0.0,1.0);
}
`;
gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader);
if(!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)){
console.log(gl.getShaderInfoLog(fragmentShader));
}
//3.3 初始化着色器程序
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.log('Could not initialise shaders');
}
gl.useProgram(program);
//3.4 创建顶点数组对象(VBO)
const vertices = [
0.0, 1.0, 0.0,
-1.0, 0.0, 0.0,
1.0, 0.0, 0.0
];
const verticesBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, verticesBufferObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
//第四步 设置canvas背景色
gl.clearColor(0.0, 0.0, 0.0, 1.0);
//第五步 清除canvas
gl.clear(gl.COLOR_BUFFER_BIT);
//第六步 绘图
const a_Position = gl.getAttribLocation(program, 'a_Position');
gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_Position);
gl.drawArrays(gl.TRIANGLES, 0, 3);
</script>
</body>
</html>