draw color and map texture in same scene in WebGL


I encounter some difficulties on drawing in color and mapping texture. If I only draw line in different color or map texture to the rectangle, it is ok. However, when I combine these two into one scene; that’s drawing in color and mapping texture in the same scene, it fails.

I think the problem is in shader script. There is an attribute called “gl_FragColor” and I can set it to gl_FragColor = vec4(vColor.rgb * lightWeighting, vColor.a); to draw in color and set it to gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); to map texture.

However, when I draw in color and map texture in the same scene, I fails to set this gl_FragColor.

Can anyone help me to solve the problem? How to set the gl_FragColor correctly? :frowning:

You need to combine the two colors calculated from lighting the vertex color and from your texture. The correct way depends on how you want the two colors to interact with each other, but a common way is to multiply the two:

vec4 litVertexColor = vec4(vColor.rgb * lightWeighting, vColor.a);
vec4 texureColor    = texture2D(uSampler, vTextureCoord.st);

gl_FragColor = litVertexColor * textureColor;

Take a look at glTexEnv (specifically the desription of GL_TEXTURE_ENV_MODE) for the options offered by the fixed function pipeline to get an idea what you might want to do.

Nice. I find an other idea from other. The method is using several shader programs. For example, in my case, I can create two shader programs: one for drawing color, one for mapping texture.