如何在WebGL中使用纹理和颜色?

Dan*_*Fox 1 javascript glsl webgl

我正在学习WebGL,我想制作一个程序,其中还有彩色和纹理对象.我尝试修改片段着色器:如果对象没有纹理,那么它将被着色.

precision mediump float;

varying vec4 vColor;
varying vec2 vTextureCoord;

uniform sampler2D uSampler;

void main(void) {
    gl_FragColor = vColor;
    gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
}
Run Code Online (Sandbox Code Playgroud)

它不起作用.我收到错误:无法初始化着色器.

gma*_*man 8

这可能有意义也可能没有意义,但无论您是否有纹理都需要不同的着色器.为了解决这个问题,许多人在不需要纹理时会使用单个像素的白色纹理.这样他们只需要1个着色器来覆盖这两种情况.着色器可能看起来像这样

uniform vec4 u_color;
uniform sampler2D u_texture;

varying vec2 v_texCoord;

void main(void) {
  gl_FragColor = texture2D(u_texture, v_texCoord) * u_color;
}
Run Code Online (Sandbox Code Playgroud)

现在,在您的代码中,您可以像这样绘制纹理

// at init time.
var whiteColor = new Float32Array([1, 1, 1, 1]);

// at draw time
gl.uniform4fv(u_colorLocation, whiteColor);  // use white color
gl.bindTexture(gl.TEXTURE_2D, someTexture);  // and some texture
... draw ...
Run Code Online (Sandbox Code Playgroud)

要绘制无纹理,你可以做到这一点

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


// at draw time
gl.uniform4fv(u_colorLocation, someColor);  // use the color I want
gl.bindTexture(gl.TEXTURE_2D, whiteTexture);  // use the white texture
... draw ...
Run Code Online (Sandbox Code Playgroud)

这也使您能够通过一起使用非白色和纹理来着色纹理.