Text Rendering Problem with Distance Field in WebGL


I made this Distance Field example with Qt OpenGL 3.3:


It works very good. I made it using this video tutorial:

I rewrote this example line by line in WebGL and it looks bad:


This problem was solved by Rabbid76:

This appears to be a problem related to Premultiplied Alpha (see Why does my WebGL alpha-transparency look wrong?.

You need to multiply the color channels by the alpha channel in the fragment shader:

void main() {
    // [...]

    vec4 color = ...;

    gl_FragColor = vec4(color.rgb * color.a, color.a);

and change the blend function to 1 * source_color + (1 -alpha) * dest_color:

gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);

Another solution that was made by _Develop:

const options: WebGLContextAttributes = {
    alpha: false, premultipliedAlpha: false
gl = (canvas as HTMLCanvasElement).getContext("webgl", options);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
precision mediump float;

varying vec2 vTexCoord;
uniform sampler2D uSampler;

const float width = 0.5;
const float edge = 0.1;

void main()
    float distance = 1.0 - texture2D(uSampler, vTexCoord).a;
    float alpha = 1.0 - smoothstep(width, width + edge, distance);
    if (alpha < 0.001)
    gl_FragColor = vec4(0.2, 0.5, 0.0, alpha);