标签:
#本文参考《WebGL编程指南》
着色器中有两种变量类型:
(1)attribute:每个顶点相关的数据
(2)uniform:每个顶点都一样的数据
#比如:每个顶点的位置都不同,则位置是attribute;如果每个顶点都是红色,则这个红色可以是uniform。
传参到着色器的步骤:
(1)在着色器里声明变量
// vertical shader var VSHADER_SOURCE = ` attribute vec4 aPos; void main() { gl_Position = aPos; gl_PointSize = 30.0; } ` // fragment shader var FSHADER_SOURCE = ` precision mediump float; uniform vec4 uColor; void main() { gl_FragColor = uColor; } `
在这里,我们声明了aPos,uColor两个变量。
ps:attribute和uniform是存储限定符
(2)找到对应的变量
attribute
var aPos = gl.getAttribLocation(gl.program, ‘aPos‘);
uniform
var uColor = gl.getUniformLocation(gl.program, ‘uColor‘);
(3)给变量赋值
attribute
gl.vertexAttrib3f(aPos, 0.5, 0.5, 0);
uniform
gl.uniform4f(uColor, 1.0, 0.0, 0.0, 1.0);
效果:
源码:
test.js
function main() { var gl = Init(); if(!gl) { console.log(‘Failed to init‘); return; } var aPos = gl.getAttribLocation(gl.program, ‘aPos‘); if(aPos < 0) { console.log(‘Failed to get the aPos‘); return; } gl.vertexAttrib3f(aPos, 0.5, 0.5, 0); var uColor = 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) function Init() { var canvas = document.getElementById(‘webgl‘); var gl = 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); return gl; }
shader.js
// vertical shader var VSHADER_SOURCE = ` attribute vec4 aPos; void main() { gl_Position = aPos; gl_PointSize = 30.0; } ` // fragment shader var FSHADER_SOURCE = ` precision mediump float; uniform vec4 uColor; void main() { gl_FragColor = uColor; } `
标签:
原文地址:http://www.cnblogs.com/programmer-kaima/p/5179604.html