attribute变量
在着色器中使用变量可以做更复杂的事
attribute vec4 a_Position;
attribute float a_PointSize;
void main() {
gl_Position = a_Position;
gl_PointSize = a_PointSize;
}
在上面的顶点着色器中,声明了attribute 变量 a_Position
attribute 是一种GLSL ES变量,被用来从外部向顶点着色器内传输数据,只有顶点着色器能使用它
从js向着色器传递数据
以下是一个示例程序
// Vertex shader program
var VSHADER_SOURCE =
`
attribute vec4 a_Position;
attribute float a_PointSize;
void main() {
gl_Position = a_Position;
gl_PointSize = a_PointSize;
}
`
// 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('webgl');
// Get the rendering context for WebGL
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;
}
// 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;
}
var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
if (a_PointSize < 0) {
console.log('Failed to get the storage location of a_PointSize');
return;
}
// Pass vertex position to attribute variable
gl.vertexAttrib3f(a_Position, 0.0, 0.0, 0.0);
gl.vertexAttrib1f(a_PointSize, 100.0);
// Specify the color for clearing <canvas>
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw
gl.drawArrays(gl.POINTS, 0, 1);
}
我们在上面的代码中,使用了下面的四行代码,来向着色器传递数据
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');//获取到a_Position变量的地址
var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');//获取到a_PointSize变量的地址
gl.vertexAttrib3f(a_Position, 0.0, 0.0, 0.0);//将数据传输给变量
gl.vertexAttrib1f(a_PointSize, 100.0);
gl.vertexAttrib3f | (location,v0,v1,v2) |
---|---|
将数据传给loaction参数指定的attribute变量 |
同族函数:
gl.vertexAttrib1f
gl.vertexAttrib2f
gl.vertexAttrib3f
gl.vertexAttrib4f
uniform变量
我们可以使用uniform来改变顶点的颜色
在以下的片元着色器中,使用了uniform变量
// Fragment shader program
var FSHADER_SOURCE =
'precision mediump float;\n' +
'uniform vec4 u_FragColor;\n' + // uniform変量
'void main() {\n' +
' gl_FragColor = u_FragColor;\n' +
'}\n';
和attribute一样,我们可以向uniform变量传递数据
获取uniform变量的存储地址:
gl.getUniformLocation(gl.program, ‘u_FragColor’);
向uniform变量赋值
gl.uniform4f(u_FragColor, rgba[0], rgba[1], rgba[2], rgba[3]);