Search code examples
colorsglslshader

How to fix this shader to properly hide alpha pixels?


i’m working on a shader that basically creates a shadow cast effect for 2D images, almost everything works except when i try to change the color of the shadow, by default the color is black and the alpha pixels are hidden, but when i adjust the color (modColor) the alpha pixels become filled with bright color

black colored

here is the shader code

vertex

uniform mat4 modelViewProjection;
attribute vec4 position;
attribute vec2 texCoord;

uniform vec4 modColor;

varying lowp vec4 vColor;
varying highp vec2 vTexCoord;
void main() {
  vColor = modColor;
  vTexCoord = texCoord;
  gl_Position = modelViewProjection * position;
}

fragment

precision highp float;
uniform lowp sampler2D texture;

varying lowp vec4 vColor;
varying highp vec2 vTexCoord;
uniform float shadowAlpha;
void main() {
  lowp vec4 bl = texture2D( texture, vTexCoord ) * vec4(0,0,0,1);
  lowp vec4 col = vec4(bl.rgb + vColor.rgb, bl.a * vColor.a);
  float useAlpha = shadowAlpha * col.a * (1.0 - vTexCoord.y);
  gl_FragColor = vec4(col.rgb, useAlpha);
}

Solution

  • Since the alpha channel of the texture (bl.a) is 0 in the areas without shadow and 1 in the areas with shadow, you can multiply the color channels of the fragment by bl.a:

    gl_FragColor = vec4(col.rgb, useAlpha);

    gl_FragColor = vec4(col.rgb * bl.a, useAlpha);