來解決這個問題最簡單的方法是使在創建時一個1x1的質感。
var tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
new Uint8Array([255, 0, 0, 255])); // red
然後,當圖像加載時,您可以用圖像替換1x1像素紋理。沒有標誌需要,你的場景將用你選擇的顏色進行渲染,直到圖像加載完畢。
var img = new Image();
img.src = "http://someplace/someimage.jpg";
img.onload = function() {
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
// then either generate mips if the image uses power-of-2 dimensions or
// set the filtering correctly for non-power-of-2 images.
setupTextureFilteringAndMips(img.width, img.height);
}
只是爲了救人運行到他們最有可能會碰到下一個問題的麻煩起見,WebGL的需要MIPS或它需要不需要MIPS過濾。最重要的是,它需要尺寸爲2的冪(即1,2,4,8,...,256,512等)的紋理才能使用mips。所以,在加載圖片時,您最有可能需要設置過濾器來正確處理此問題。
function isPowerOf2(value) {
return (value & (value - 1)) == 0;
};
function setupTextureFilteringAndMips(width, height) {
if (isPowerOf2(width) && isPowerOf2(height) {
// the dimensions are power of 2 so generate mips and turn on
// tri-linear filtering.
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
} else {
// at least one of the dimensions is not a power of 2 so set the filtering
// so WebGL will render it.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
}
感謝您提出這個問題,我一直在這些控制檯消息中進行一段時間的實驗。 :-) –