#本文参考 The WebGL Programming Guide
There are two types of variables in the shader:
(1) attribute: Data related to each vertex
(2) Uniform: the same data for each vertex
#比如: Each vertex has a different position, the position is attribute, and if each vertex is red, the red can be uniform.
To pass a parameter to a shader:
(1) Declaring a variable in a shader
// Vertical Shader var Vshader_source = ' attribute vec4 aPos; void Main () { = aPos; = 30.0; } '// fragment shadervar fshader_source = ' float ; Uniform vec4 Ucolor; void Main () { = ucolor; } `
Here we declare a apos,ucolor of two variables.
Ps:attribute and uniform are storage qualifiers
(2) Find the corresponding variable
Attribute
var aPos = gl.getattriblocation (Gl.program, ' APos ');
Uniform
var ucolor = gl.getuniformlocation (Gl.program, ' ucolor ');
(3) Assigning a value to a variable
Attribute
GL.VERTEXATTRIB3F (APos, 0.5, 0.5, 0);
Uniform
gl.uniform4f (Ucolor, 1.0, 0.0, 0.0, 1.0);
Effect:
Source:
Test.js
functionMain () {varGL =Init (); if(!GL) {Console.log (' Failed to Init '); return; } varAPos = Gl.getattriblocation (Gl.program, ' APos '); if(APos < 0) {Console.log (' Failed to get the APos '); return; } gl.vertexattrib3f (APos,0.5, 0.5, 0); varUcolor = Gl.getuniformlocation (Gl.program, ' Ucolor '); if(Ucolor < 0) {Console.log (' Failed to get the Ucolor '); return; } gl.uniform4f (Ucolor,1.0, 0.0, 0.0, 1.0); Gl.drawarrays (GL. POINTS,0, 1);}//@Func: init the WebGL//@Return: GL (the WebGL context)functionInit () {varCanvas = document.getElementById (' WebGL '); varGL =getwebglcontext (canvas); if(!GL) {Console.log (' Failed to get the rendering context for WebGL '); return NULL; } if(!initshaders (GL, Vshader_source, Fshader_source)) {Console.log (' Failed to init shader '); return NULL; } gl.clearcolor (0.0, 1.0, 1.0, 1.0); Gl.clear (GL. Color_buffer_bit); returnGL;}
View Code
Shader.js
// Vertical Shader var Vshader_source = ' attribute vec4 aPos; void Main () { = aPos; = 30.0; } '// fragment shadervar fshader_source = ' float ; Uniform vec4 Ucolor; void Main () { = ucolor; } `
View Code
WebGL (3)--parameter to shader