Search code examples
javascriptglslwebgl

Webgl adding a background to an image


So I am new to Webgl and have been trying to add a transparent background so you can still see the image but also the background. I've included the code I've been working with but everytime i run the code it just posts the image and doesn't change the background. Any tips on what I'm doing wrong would be appreciated.

precision highp float;
    
// Uniform variables are constant over image
uniform float time;
uniform sampler2D image;
uniform vec2 u_resolution;
uniform vec2 viewport;
    
void main(void)
{
    gl_FragColor = vec4(1.0, 0.0, 0.0, 0.5);
    gl_FragColor = texture2D(image, gl_FragCoord.yx / 600.0);
}

Solution

  • It depends on what you want. You can mix the texture color and the background color 1:1:

    void main(void)
    {
        vec4 color = vec4(1.0, 0.0, 0.0, 0.5);
        vec4 textureColor = texture2D(image, gl_FragCoord.yx / 600.0);
        gl_FragColor = mix(textureColor, color, 0.5);
    }
    


    If the texture is partially transparent and you want to fill tis areas with the background color, you must mix the color depending on the alpha channel of the texture (textureColor.a):

    void main(void)
    {
        vec4 backColor = vec4(1.0, 0.0, 0.0, 0.5);
        vec4 textureColor = texture2D(image, gl_FragCoord.yx / 600.0);
        gl_FragColor = mix(backColor, textureColor, textureColor.a);
    }
    

    However, Blending is something completely different. Blending needs to be enabled and the blend function must be set. This cannot be done in the sharer. It must be set up using WebGL instructions. e.g.:

    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
    

    See also Does blending work with the GLSL mix function