1

如何在 WebGL 中使用纹理数组(包含不同的图像)而不分别初始化每个纹理?我想显示一个立方体和一个金字塔(组织为一个数组),每个都有不同的纹理图像。这是代码的一部分(用于初始化纹理):

function handleTexture(texture) {
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.Img);
    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);
}

function initTextures() {
    for (i=0; i<2; i++) {
        tex[i] = gl.createTexture();
        tex[i].Img = new Image();
        tex[i].Img.onload = function() { handleTexture(tex[i]); }
        tex[i].Img.src = texImgs[i];   // The name of the image file
    }
}

立方体和金字塔显示为黑色(无纹理),我在页面中收到此错误:

Uncaught TypeError: Cannot read property 'Img' of undefined  // gl.texImage2D()
tex.(anonymous function).Img.onload                          // tex[i].Img.onload = ...

如果我单独初始化纹理,而不是使用数组,而是使用 tex1 和 tex2,我没有这个错误。关于如何使用数组执行此操作的任何建议?

4

1 回答 1

1

When you do:

tex[i] = gl.createTexture();

tex[i] becomes a type of WebGLTexture and you cannot attach new properties on that object as you did with .Img property. So slightly more correct version would be:

var tex = [], texImgs = ['pyra.jpg', 'cube.jpg'];

function handleTexture(myTexture) {
    myTexture.texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, myTexture.texture);

    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, myTexture.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);
}

function initTextures() {
    for (var i=0; i<2; i++) {
        (function(index) {
            tex[index] = new Object();
            tex[index].texture = null;
            tex[index].image = new Image();
            tex[index].image.onload = function() { handleTexture(tex[index]); }
            tex[index].image.src = texImgs[index];   // The name of the image file
        })(i);
    }
}

Note that you create an object that has image and texture property separated.

Hope this helps you.

EDIT:

Closure messes the index of the tex.

于 2013-09-06T09:37:58.440 回答