これを修正する最も簡単な方法は、作成時に 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 など) の寸法のテクスチャが必要です。そのため、画像をロードするときは、これを正しく処理するようにフィルタリングを設定する必要があります。
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);
}
}