目前,有关Web中纹理的许多WebGL教程都是关于向动画对象添加纹理。我只是试图将一个纹理添加到一个静态对象(立方体的三面),它不起作用;对象显示为黑色。以下是代码的一部分:
function initBuffers() {
VBuffer = gl.createBuffer(); // 3D vertices
gl.bindBuffer(gl.ARRAY_BUFFER, VBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(Verts), gl.STATIC_DRAW);
FBuffer = gl.createBuffer(); // Facet definition
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, FBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(Faces), gl.STATIC_DRAW);
vTBuffer = gl.createBuffer(); // Texture coordinates
gl.bindBuffer(gl.ARRAY_BUFFER, vTBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vTex), gl.STATIC_DRAW);
}
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() {
tex1 = gl.createTexture();
tex1.Img = new Image();
tex1.Img.onload = function() { handleTexture(tex1); }
tex1.Img.src = texImgs[0]; // "cubetexture.png"
}
function drawScene() {
...
gl.bindBuffer(gl.ARRAY_BUFFER, VBuffer);
gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, vTBuffer);
gl.vertexAttribPointer(texCoordAttribute, 2, gl.FLOAT, false, 0, 0);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, tex1);
gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, FBuffer);
setMatrixUniforms();
gl.drawElements(gl.TRIANGLES, nVF, gl.UNSIGNED_SHORT, 0);
}
这些函数在加载页面时被调用,如下所示:
...
initBuffers();
initTextures();
drawScene();
但我得到的只是一个黑色物体。有任何建议如何解决这个问题?
答案 0 :(得分:1)
在加载并处理纹理(也就是准备使用)之后,再次调用drawScene()
以便可以拾取纹理。
function handleTexture(texture) {
// code....
gl.bindTexture(gl.TEXTURE_2D, null);
drawScene();
}