今天学习<<javascript高级程序设计(第三版)>>的15.3WebGL部分的时候,运行书上的代码时在chrome和firefox浏览器下都报错如下:
WebGL.html:81 WebGL: INVALID_OPERATION: useProgram: program not valid
WebGL.html:83 WebGL: INVALID_OPERATION: getUniformLocation: program not linked
WebGL.html:85 WebGL: INVALID_OPERATION: getAttribLocation: program not linked
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>WebGL</title>
</head>
<body>
<canvas id="drawing">浏览器不支持canvas</canvas>
<script type="x-webgl/x-vertex-shader" id="vertexShader">
attribute vec2 aVertexPosition;
void main (void) {
gl_Position = vec4(aVertexPosition, 0, 1.0);
}
</script>
<script type="x-webgl/x-fragment-shader" id="fragmentShader">
uniform vec4 uColor;
void main (void) {
gl_FragColor = uColor;
}
</script>
<script type="text/javascript">
var drawing = document.getElementById("drawing"),
gl;
drawing.width = 400;
drawing.height = 400;
try {
gl = drawing.getContext("experimental-webgl");
} catch (ex) {
}
if(gl) {
// 先用实色清除canvas
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
// 视口
gl.viewport(0, 0, drawing.width, drawing.height);
// 创建缓冲区
var buffer = gl.createBuffer();
// 绑定到WebGL上下文
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
// 用数据填充缓冲区
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0.5, 1]), gl.STATIC_DRAW);
// 创建着色器
var vertexGlsl = document.getElementById("vertexShader").text;
var fragmentGlsl = document.getElementById("fragmentShader").text;
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexGlsl);
gl.compileShader(vertexShader);
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentGlsl);
gl.compileShader(fragmentShader);
// 调试代码,alert的内容为ERROR: 0:2:" :No precision specified for (float)
if(!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(fragmentShader));
}
// 把两个对象链接到着色器程序中
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);
// 为着色器传入值
var uColor = gl.getUniformLocation(program, "uColor");
gl.uniform4fv(uColor, [0, 0, 0, 1]);
var aVertexPosition = gl.getAttribLocation(program, "aVertexPosition");
gl.enableVertexAttribArray(aVertexPosition);
gl.vertexAttribPointer(aVertexPosition, 1, gl.FLOAT, false, 0, 0);
} else {
alert("gl is not exist");
}
</script>
</body>
</html>
经过测试,问题应该就是出在fragmentShader。但是将错误语句ERROR: 0:2:" :No precision specified for (float) 搜索后也没有找到原因和解决方案。请高手帮忙看看,谢谢啦
看过但没有明白的网址:http://stackoverflow.com/questions/11998781/webgl-invalid-operation-useprogram
很简单的小问题,它不是提示你了嘛,片段着色器第二行缺少精度描述,片段着色器必须加入精度描述,把24~26加进去,