我建議using some boilerplate code編譯你的着色器和鏈接程序
對於着色器
/**
* Creates and compiles a shader.
*
* @param {!WebGLRenderingContext} gl The WebGL Context.
* @param {string} shaderSource The GLSL source code for the shader.
* @param {number} shaderType The type of shader, VERTEX_SHADER or
* FRAGMENT_SHADER.
* @return {!WebGLShader} The shader.
*/
function compileShader(gl, shaderSource, shaderType) {
// Create the shader object
var shader = gl.createShader(shaderType);
// Set the shader source code.
gl.shaderSource(shader, shaderSource);
// Compile the shader
gl.compileShader(shader);
// Check if it compiled
var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!success) {
// Something went wrong during compilation; get the error
throw "could not compile shader:" + gl.getShaderInfoLog(shader);
}
return shader;
}
對於節目
/**
* Creates a program from 2 shaders.
*
* @param {!WebGLRenderingContext) gl The WebGL context.
* @param {!WebGLShader} vertexShader A vertex shader.
* @param {!WebGLShader} fragmentShader A fragment shader.
* @return {!WebGLProgram} A program.
*/
function createProgram(gl, vertexShader, fragmentShader) {
// create a program.
var program = gl.createProgram();
// attach the shaders.
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
// link the program.
gl.linkProgram(program);
// Check if it linked.
var success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!success) {
// something went wrong with the link
throw ("program filed to link:" + gl.getProgramInfoLog (program));
}
return program;
}
你可以這樣調用
着色器
var vertShader = compileShader(gl, vertShaderSource, gl.VERTEX_SHADER);
var fragShader = compileShader(gl, fragShaderSource, gl.FRAGMENT_SHADER);
var program = createProgram(gl, vertShader, fragShader);
如果着色器不編譯或鏈接,應該將錯誤信息打印到JavaScript控制檯。它也應該給你堆棧跟蹤,所以你可以告訴你代碼中的問題在哪裏。
您是否檢查過您的着色器是否已編譯?調用'gl.compileShader'後,調用'gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)'。如果返回false,則着色器出現錯誤,這可能會阻止WebGL繼續設置程序。 – radical7
是的,着色器正在編譯。這不是連接 –