with and without texture


I just started learning webGL.
I’m following the great http://www.learningwebgl.com tutorials but I have great difficulties in creating my own stuff. I also have almost no openGL experience.

What I want to do now is to show cube with texture (lesson 5 tutorial) and a line.
For now, if I use the shaders like they are in the tutorial, the line gets the color of the texture.
If I use a simple shader passing the color given in a color buffer then I get my line to be gray as I want it to be, but the cube with the texture disappears, since it has only texture color.
How can I write a shader that gives a color I want to to a shape and maps the texture on shapes that have texture.
Or in general, if i want some objects with texture and some without in my scene, how do you do that?

The simple answer is “in the world of shaders you can’t”

You either need separate shaders, 1 for textures, 1 without or you need to get creative. A common way games do it is make a pixel shader like this

  varying vec2 vTextureCoord;

  uniform sampler2D uSampler;
  uniform vec4 uColorMult;

  void main(void) {
    gl_FragColor = texture2D(
       uSampler, vec2(vTextureCoord.s, vTextureCoord.t)) * uColorMult;

Then you make a 1 pixel white texture.

var whiteTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, whiteTexture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
new Uint8Array([255,255,255,255]));

When you want to draw just a texture you set colorMult to 1,1,1,1 and uSampler to your texture. When you want to draw a solid color you set colorMult to the color you want and uSampler to the white texture.

This kind of technique also has the advantage that you can tint your textures different colors (like if you were making avatars and you want the user to be able to change the color a textured shirt).

Isn’t it possible to just add some vertex attribute, f.e. “noTex” and for line set it to true and false for the rest? Then in shader you could use / not use texture

if (noTex) {
  gl_FragColor = compute color w/o texture
} else {
  gl_FragColor = texture2D...