这是源代码,非常简单,但不起作用。 //这是html文件
<html>
<head>
<title>Test</title>
<style>
body { background: pink }
canvas { background: orange }
</style>
<script src="utils.js"></script>
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec4 aVertexPosition;
void main() {
gl_PointSize = 10.0;
gl_Position = aVertexPosition;
}
</script>
<script id="shader-fs" type="x-shader/x-fragment">
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
</script>
<script>
var canvas, gl, shaderProgram;
window.onload = function() {
initCanvasAndGL("canvas", canvas, gl);console.log(gl);
initProgram(gl, shaderProgram);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
var aVertexPosition = gl.getAttribLocation(shaderProgram, "aVertexPosition");
canvas.onmousedown = function(e) {
onCanvasMouseDown(e, aVertexPosition, canvas, gl);
}
}
function onCanvasMouseDown(e, aVertexPosition, canvas, gl) {
var x = e.pageX;
var y = e.pageY;
x = (x - canvas.width / 2) / (canvas.width / 2);
y = (canvas.height / 2 - y) / (canvas.height / 2);
gl.vertexAttrib2f(aVertexPosition, x, y);
gl.drawArray(gl.POINTS, 0, 1);
}
</script>
</head>
<body>
<canvas id="canvas" width="400" height="400">
Canvas Not Supported! :(
</canvas>
</body>
</html>
and this is the utils.js file
function initCanvasAndGL(canvasID, canvas, gl) {
canvas = document.getElementById(canvasID);
var names = [
"webgl", "experimental-webgl",
"webkit-3d", "moz-webgl"
];
for(var i = 0; i < names.length; ++i) {
try {
gl = canvas.getContext(names[i]);console.log("i: " + i + "gl: " + gl);
} catch(e) {}
if(gl) {
break;
}
}
if(!gl) {
alert("WebGL is not available! :(");
}
}
function getShader(gl, id) {
var shaderScript = document.getElementById(id);
if(!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while(k) {
if(k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if(shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else if(shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.complieShader(shader);
if(!gl.getShaderParameter(shader, gl.COMPLIE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function initProgram(gl, shaderProgram) {
var vertexShader = getShader(gl, "shader-vs");
var fragmentShader = getShader(gl, "shader-fs");
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if(!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders! :(");
}
gl.useProgram(shaderProgram);
}
控制台跟踪Uncaught TypeError:无法读取undefined的属性'VERTEX_SHADER'。所以我在window.onload()函数和initCanvasAndGL()函数中添加了两个console.log()。结果是: i:0gl:null utils.js:10 i:1gl:[object WebGLRenderingContext] utils.js:10 未定义 我真的不知道为什么!谁能帮我?感谢。