下面将从一个画一个三角形来介绍webgl程序的流程,大致执行流程如下图所示:
    webgl执行流程.png
    下面从上图的WebGL的大致流程实现如何画一个三角形:

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>webgl第一课——画一个三角形</title>
    7. <style>
    8. html,body {
    9. padding: 0;
    10. margin: 0;
    11. }
    12. canvas{
    13. margin: 50px;
    14. }
    15. </style>
    16. </head>
    17. <body>
    18. <canvas height="800px" width="800px" id="canvas"></canvas>
    19. <script>
    20. // 第一步 获取canvas对象
    21. const canvas = document.getElementById('canvas');
    22. // 第二步 获取WebGL上下文
    23. const gl = canvas.getContext('webgl');
    24. //第三步 初始化着色器
    25. // 3.1 初始化顶点着色器
    26. const vertexShader = gl.createShader(gl.VERTEX_SHADER);
    27. const vertexShaderSource = `
    28. attribute vec4 a_Position;
    29. void main(){
    30. gl_Position = a_Position;
    31. }
    32. `;
    33. gl.shaderSource(vertexShader, vertexShaderSource);
    34. gl.compileShader(vertexShader);
    35. if(!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)){
    36. console.log(gl.getShaderInfoLog(vertexShader));
    37. }
    38. //3.2 初始化片元着色器
    39. const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
    40. const fragmentShaderSource = `
    41. void main(){
    42. gl_FragColor = vec4(1.0,0.0,0.0,1.0);
    43. }
    44. `;
    45. gl.shaderSource(fragmentShader, fragmentShaderSource);
    46. gl.compileShader(fragmentShader);
    47. if(!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)){
    48. console.log(gl.getShaderInfoLog(fragmentShader));
    49. }
    50. //3.3 初始化着色器程序
    51. const program = gl.createProgram();
    52. gl.attachShader(program, vertexShader);
    53. gl.attachShader(program, fragmentShader);
    54. gl.linkProgram(program);
    55. if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    56. console.log('Could not initialise shaders');
    57. }
    58. gl.useProgram(program);
    59. //3.4 创建顶点数组对象(VBO)
    60. const vertices = [
    61. 0.0, 1.0, 0.0,
    62. -1.0, 0.0, 0.0,
    63. 1.0, 0.0, 0.0
    64. ];
    65. const verticesBufferObject = gl.createBuffer();
    66. gl.bindBuffer(gl.ARRAY_BUFFER, verticesBufferObject);
    67. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    68. //第四步 设置canvas背景色
    69. gl.clearColor(0.0, 0.0, 0.0, 1.0);
    70. //第五步 清除canvas
    71. gl.clear(gl.COLOR_BUFFER_BIT);
    72. //第六步 绘图
    73. const a_Position = gl.getAttribLocation(program, 'a_Position');
    74. gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, 0, 0);
    75. gl.enableVertexAttribArray(a_Position);
    76. gl.drawArrays(gl.TRIANGLES, 0, 3);
    77. </script>
    78. </body>
    79. </html>