TinySDF
TinySDF is a tiny and fast JavaScript library for generating SDF (signed distance field)
from system fonts on the browser using Canvas 2D and
Felzenszwalb/Huttenlocher distance transform.
This is very useful for rendering text with WebGL.
Usage
Create a TinySDF for drawing glyph SDFs based on font parameters:
const tinySdf = new TinySDF({
fontSize: 24,
fontFamily: 'sans-serif',
fontWeight: 'normal',
fontStyle: 'normal',
buffer: 3,
radius: 8,
cutoff: 0.25
});
const glyph = tinySdf.draw('泽');
Returns an object with the following properties:
data
is a Uint8ClampedArray
array of alpha values (0–255) for a width
x height
grid.width
: Width of the returned bitmap.height
: Height of the returned bitmap.glyphTop
: Maximum ascent of the glyph from alphabetic baseline.glyphLeft
: Currently hardwired to 0 (actual glyph differences are encoded in the rasterization).glyphWidth
: Width of the rasterized portion of the glyph.glyphHeight
Height of the rasterized portion of the glyph.glyphAdvance
: Layout advance.
TinySDF is provided as a ES module, so it's only supported on modern browsers, excluding IE.
<script type="module">
import TinySDF from 'https://cdn.skypack.dev/@mapbox/tiny-sdf';
...
</script>
In Node, you can't use require
— only import
in ESM-capable versions (v12.15+):
import TinySDF from '@mapbox/tiny-sdf';
Development
npm test
npm start
License
This implementation is licensed under the BSD 2-Clause license. It's based directly on the algorithm published in the Felzenszwalb/Huttenlocher paper, and is not a port of the existing C++ implementation provided by the paper's authors.