2
votes

I tryed to put data in the fragment shader to color 2 triangles through textures, but the color given is black (maybe default?), not green or red as expected.

The source from where I tryed to do that is https://webglfundamentals.org/webgl/lessons/webgl-shaders-and-glsl.html#textures-in-fragment-shaders. I put everything from there in my source and I thought that if I put a green pixel with a red pixel in my texture, then it needs to have a different color than black, but was black.

That's the fragment shader:

precision mediump float;

uniform sampler2D u_texture;

void main() {
   vec2 texcoord = vec2(0.5, 0.5)  // get a value from the middle of the texture
   gl_FragColor = texture2D(u_texture, texcoord);
}

There I created the texture and I put data in it.

var tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
var level = 0;
var width = 2;
var height = 1;
var data = new Uint8Array([
   255, 0, 0, 255,   // a red pixel
   0, 255, 0, 255,   // a green pixel
]);
gl.texImage2D(gl.TEXTURE_2D, level, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);

I tried to put different data in the texture with even another colors, but the result was the same.

1

1 Answers

0
votes

You've to set the texture minifying function to a "non mipmap" filter, else the texture is not mipmap complete. e.g.:

gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);

By default the minifing parameter is NEAREST_MIPMAP_LINEAR. This parameter value requires a mipmap for the texture, to be complete.

The other option is to generate mipmaps by:

gl.generateMipmap(gl.TEXTURE_2D)

But for that the width and the height of the texture have to be a power of two (for WebGL 1.0). See WebGL specification - 5.13.8 Texture objects.

Note, if a texture is not mipmap complete, then the return value of a texel fetch is (0, 0, 0, 1), this causes the "black" color.