Javascript:为什么“纹理”参数没有定义?
我是Javascript新手,我正在玩WebGL,得到一个错误,下面的代码中没有定义texture.image。当我使用Firebug调试它时,this.starshipTexture.image被初始化并与图像文件一起加载,但当调用handleLoadedTexturetexture时,纹理参数显示为未定义Javascript:为什么“纹理”参数没有定义?,javascript,webgl,Javascript,Webgl,我是Javascript新手,我正在玩WebGL,得到一个错误,下面的代码中没有定义texture.image。当我使用Firebug调试它时,this.starshipTexture.image被初始化并与图像文件一起加载,但当调用handleLoadedTexturetexture时,纹理参数显示为未定义 starship.prototype.initTexture = function () { var starshipImage = new Image();
starship.prototype.initTexture = function () {
var starshipImage = new Image();
this.starshipTexture = gl.createTexture();
this.starshipTexture.image = starshipImage;
starshipImage.onload = function () {
handleLoadedTexture(this.starshipTexture)
}
starshipImage.src = "starship.gif";
}
function handleLoadedTexture(texture) {
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.bindTexture(gl.TEXTURE_2D, texture);
//CRASHES ON THIS NEXT LINE
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
gl.generateMipmap(gl.TEXTURE_2D);
gl.bindTexture(gl.TEXTURE_2D, null);
}
谢谢你的智慧 问题在于,在这个加载处理程序中,它不是您所需要的
相反,在设置处理程序之前,将其填充到临时变量中:
var theStarship = this;
starshipImage.onload = function () {
handleLoadedTexture(theStarship.starshipTexture)
};
问题是,在这个加载处理程序中,它并不是您所需要的
相反,在设置处理程序之前,将其填充到临时变量中:
var theStarship = this;
starshipImage.onload = function () {
handleLoadedTexture(theStarship.starshipTexture)
};
为了补充Pointy的答案,您可以利用出色的javascript duck类型:
starshipImage.targetObject = this;
starshipImage.onload = function () {
handleLoadedTexture(this.targetObject.starshipTexture)
};
为了补充Pointy的答案,您可以利用出色的javascript duck类型:
starshipImage.targetObject = this;
starshipImage.onload = function () {
handleLoadedTexture(this.targetObject.starshipTexture)
};
波蒂的答案的另一个选择是使用我觉得更优雅的答案,但做同样的事情,通常是一个选择的问题
starshipImage.onload = handleLoadedTexture.bind(window, this.starshipTexture);
这就创建了一个绑定函数,也就是一个函数,在这个函数中上下文是this,在这个例子中不需要它,函数的参数在调用函数之前被设置。Pointy的答案的替代方法是使用我觉得更优雅的方法,但是做同样的事情,通常是一个选择问题
starshipImage.onload = handleLoadedTexture.bind(window, this.starshipTexture);
这将创建一个绑定函数,即,在调用函数之前设置上下文(本例中不需要)和函数参数的函数。或者您可以使用function.bind starshipImage.onload=handleLoadedTexture.bindwindow,this.starshipTexture或者您可以使用Function.bind starshipImage.onload=handleLoadedTexture.bindwindow,this.starshipTexture仅为此附加一个额外属性是浪费资源和黑客行为。局部变量更有意义。仅仅为了这个目的附加一个额外的属性是浪费资源和黑客行为。局部变量更有意义。