当前位置: 首页 > 工具软件 > webGL-Shaders > 使用案例 >

WebGl-5.通过attribute变量传值

阳长恨
2023-12-01

attribute变量是一种GLSL ES变量,被用来从外部向顶点着色器内传输数据。使用attribute变量,包含一下步骤:

  1. 在顶点着色器中,声明attribute变量。
  2. 将attribute变量赋值给gl_Position变量。
  3. 向attribute变量传输数据。

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/static/css/common.css">
    <title>attribute</title>
</head>
<body onload="main()">
    <canvas id="example" width="512" height="512">
        游览器不支持
    </canvas>
</body>
<script src="/static/js/cuon-utils.js"></script>
<script src="/static/js/webgl-debug.js"></script>
<script src="/static/js/webgl-utils.js"></script>
<script>
        var VSHADER_SOURCE = 
        'attribute vec4 a_Position;\n' + // attribute variable
        'void main() {\n' +
        '  gl_Position = a_Position;\n' +
        '  gl_PointSize = 10.0;\n' +
        '}\n'; 

        // Fragment shader program
        var FSHADER_SOURCE = 
        'void main() {\n' +
        '  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
        '}\n';

        function main() {
            // Retrieve <canvas> element
            var canvas = document.getElementById('example');
            console.log(canvas)
            // Get the rendering context for WebGL
            // var gl = getWebGLContext(canvas);
            var gl = canvas.getContext('webgl');
            if (!gl) {
                console.log('Failed to get the rendering context for WebGL');
                return;
            }

            // Initialize shaders
            if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
                console.log('Failed to intialize shaders.');
                return;
            }

            // Get the storage location of a_Position
            var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
            if (a_Position < 0) {
                console.log('Failed to get the storage location of a_Position');
                return;
            }

            // Pass vertex position to attribute variable
            gl.vertexAttrib3f(a_Position, 1.0, 0.0, 0.0);

            // Specify the color for clearing <canvas>
            gl.clearColor(0.0, 0.5, 0.5, 1.0);

            // Clear <canvas>
            gl.clear(gl.COLOR_BUFFER_BIT);
                
            // Draw
            gl.drawArrays(gl.POINTS, 0, 1);
        }
</script>
</html>

 类似资料: