当前位置:网站首页>Getting started with webgl (3)

Getting started with webgl (3)

2022-07-07 15:39:00 Vegetable chicken on the road

Use attribute Variable

Purpose of use : Transfer location information from js Passed to vertex shaders in code , There are two main ways ,attribute Variables and uniform Variable ;
attribute Variable : Data related to vertices ;
uniform Variable : So the vertices are the same ( Vertex independent ) data .
Code up :

//  Vertex shader program 
var VSHADER_SOURCE =
    'attribute vec4 a_Position;\n'+
    'void main() {\n' +
    '  gl_Position = a_Position ;\n' + 
    '  gl_PointSize = 30.0;\n' +                   
    '}\n';

//  Chip shader program 
var FSHADER_SOURCE =
    'void main() {\n' +
    '  gl_FragColor = vec4(1.0, 0.5, 0.0, 1.0);\n' +
    '}\n';
function main() {
    //  obtain  <canvas>  Elements 
    var canvas = document.getElementById('webgl');

    //  obtain WebGL Rendering context 
    var gl = getWebGLContext(canvas);
    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;
    }

    // obtain attribute Storage location 
    let a_Position = gl.getAttribLocation(gl.program,"a_Position");
    if(a_Position < 0){
        console.log(" Failed to get storage location !");
        return;
    }

    // Pass the vertex position to attribute Variable 
    // gl.vertexAttrib1f(a_Position,0.0);
    // gl.vertexAttrib2f(a_Position,0.0,0,0);
    gl.vertexAttrib3f(a_Position,0.0,0.0,0.0);

    //  Specify empty <canvas> The color of the 
    gl.clearColor(0.0, 0.0, 0.0, 1.0);

    //  Empty <canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);

    //  Draw a point 
    gl.drawArrays(gl.POINTS, 0, 1);
}

Above , The process is :
(1)attribute vec4 a_Position Variables are declared in attribute, Must be a global variable , Passed in from outside the shader ;
(2) Use getAttribLocation Method to get attribute The address of the variable , The value returned >=0 It means that the address of the variable is returned ,=-1 It means that the variable does not exist ;
(3) Use vertexAttrib3f Method pass value .
This method has 3 Homologous functions , Represents the incoming 1-4 It's worth ,, The length of the array of numbers to be changed in the function . If declared attribute A variable is vec4 type , Only incoming 1 Parameters , The default complement of the last two components is 0.0, The last component is 1.0;
(4) draw , Or draw a dot , It's just to change the way of external value transfer

原网站

版权声明
本文为[Vegetable chicken on the road]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130612339933.html