我正在尝试在javascript中创建一个包含3dObject的对象以及与之相关的每个对象:顶点位置,法线,纹理坐标等等+处理它的方法:加载对象,绘图等。
问题在于,当我尝试解析WebGL上下文对象时,在我的情况下gl,它被声明为全局,为了使用特定的方法,如createBuffer(),bindBuffer(),javascript给我以下错误:“未捕获的TypeError:无法调用未定义的方法'createBuffer'“
这是目标代码:
function object3D(gl){
this.vertexPositionBuffer = gl.createBuffer();
this.textureCoordBuffer = gl.createBuffer();
this.normalDirectionBuffer = gl.createBuffer();
this.indexBuffer = gl.createBuffer();
this.loadVertices = function (vertices, itemSize, numItems){
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexPositionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
this.vertexPositionBuffer.numItems = numItems;
this.vertexPositionBuffer.itemSize = itemSize;
}
this.loadNormals = function (normals, itemSize, numItems){
gl.bindBuffer(gl.ARRAY_BUFFER, this.normalDirectionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);
this.normalDirectionBuffer.numItems = numItems;
this.normalDirectionBuffer.itemSize = itemSize;
}
this.loadIndex = function (indexArray, itemSize, numItems){
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array, gl.STATIC_DRAW);
this.indexBuffer.numItems = numItems;
this.indexBuffer.itemSize = itemSize;
}
this.loadTexture = function (textureCoord, itemSize, numItems){
gl.bindBuffer(gl.ARRAY_BUFFER, this.textureCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoord), gl.STATIC_DRAW);
this.textureCoordBuffer.numItems = numItems;
this.textureCoordBuffer.itemSize = itemSize;
}
}
这是我尝试创建此对象的实例的方法:
var cube1 = new object3D(gl);
WebGL上下文分配:
var gl;
function initGL(canvas){
try{
gl = canvas.getContext("experimental-webgl");
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
}catch(e){
}
if(!gl){
alert("Could not initialise WebGL");
}
}
在任何函数之外和我的对象定义中,console.log(gl)说是未定义的,但在其他地方它工作得很好,尽管它被声明为全局。
我必须提到我在c ++中有扎实的背景,但我对javascript和处理对象都很陌生。