WebGL

示例6:绘制三角形

2021-06-29  本文已影响0人  WebGiser

效果

image.png

代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
        
        </style>
    </head>
    <body>
        <canvas id="canvas" width="600" height="600" style="border: 1px solid #ff0000;"></canvas>
        
        <script>
            let canvas = document.getElementById('canvas');
            let gl = canvas.getContext('webgl');
            
            // 顶点着色器
            let VSHADER_SOURCE = 
            "attribute vec4 a_Position;\n"+
            "void main(){\n"+
                "gl_Position = a_Position;\n"+
            "}\n";
            
            // 片元着色器
            let FSHADER_SOURCE = 
            "void main(){\n"+
                "gl_FragColor = vec4(1.0, 0.0 ,0.0, 1.0);\n"+
            "}\n";
            
            
            // 初始化着色器
            function initShaders(gl, vSource, fSource){
                let vShader = gl.createShader(gl.VERTEX_SHADER);
                gl.shaderSource(vShader, vSource);
                gl.compileShader(vShader);
                
                let fShader = gl.createShader(gl.FRAGMENT_SHADER);
                gl.shaderSource(fShader, fSource);
                gl.compileShader(fShader);
                
                let program = gl.createProgram();
                gl.attachShader(program, vShader);
                gl.attachShader(program, fShader);
                gl.linkProgram(program);
                gl.useProgram(program);
                gl.program = program;
            }
            
            // 设置定点位置-缓冲区对象
            function initVertexBuffers(gl){
                let vertices = new Float32Array([
                    0.0, 0.5, -0.5, -0.5, 0.5, -0.5
                ]);
                let n = 3;
                // 创建缓冲区对象
                let vertexBuffer = gl.createBuffer();
                // 将缓冲区对象绑定到目标
                gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
                // 向缓冲区对象中写入数据
                gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
                // 将缓冲区对象分配给a_Position
                let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
                gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
                // 连接a_Position变量与分配给它的缓冲区对象
                gl.enableVertexAttribArray(a_Position);
                return n;
            }
            
            initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE);
            
            initVertexBuffers(gl);
            
            gl.clearColor(0.0, 0.0, 0.0, 1.0);
            gl.clear(gl.COLOR_BUFFER_BIT);
            
            gl.drawArrays(gl.TRIANGLES, 0, 3);
        </script>
    </body>
</html>

上一篇下一篇

猜你喜欢

热点阅读