2
votes

Core Problem:

I want to render Text in WebGL.

I don't want to do this via an "overlayed" HTML DOM Element.

I want the actual text rendering to happen inside WebGL.

Initial Solution 1

Render each character as a high number of quads. This is not good as I need to render many characters.

Initial Solution 2 (implemented + tried this one).

Using Canvas, render all characters into an "atlas/map".

Convert Canvas into a WebGL Texture.

When I need to render a character, just pull it from the Texture.

Problem: Even if the Canvas renders the font at font size 80, and the WebGL renders the font at font size 20, it's still blurry due to various forms of antialiasing, interpolation, and whatever else post processing.

What I think is the right solution. (Not sure, may be wrong on this).

Signed Distance Field: https://www.youtube.com/watch?v=CGZRHJvJYIg

For every pixel, store distance to nearest border.

Question

I am having trouble finding any WebGL implementation of Signed Distance Fields.

  1. Can SDFs work with WebGL, or is there some limitation of WebGL which prevents SDFs from working.

  2. If so, is there some library that will take are of:

    • actual shader for rendering SDF AND
    • can take a font and produce the SDFs necessary for rendering?

EDIT: Can someone please verify that the following is a COMPLETE SDF shader?

(copied from https://www.mapbox.com/blog/text-signed-distance-fields/ )

precision mediump float;

uniform sampler2D u_texture;
uniform vec4 u_color;
uniform float u_buffer;
uniform float u_gamma;

varying vec2 v_texcoord;

void main() {
    float dist = texture2D(u_texture, v_texcoord).r;
    float alpha = smoothstep(u_buffer - u_gamma, u_buffer + u_gamma, dist);
    gl_FragColor = vec4(u_color.rgb, alpha * u_color.a);
}
1

1 Answers

1
votes

Yes, SDF's perfectly suitable for a WebGL application. For example, Mapbox uses it. The post actually contains SDF shader since it's incredibly simple.

To the second part of your question: it's better to prepare SDF texture for a font beforehand, and there're instruments to do exactly that. This one, for example.