Repository: mattdesl/fontpath
Branch: master
Commit: b29141620e5d
Files: 8
Total size: 13.7 KB
Directory structure:
gitextract_0tfz4ibk/
├── .gitignore
├── bin/
│ └── fontpath
├── lib/
│ ├── SimpleJson.js
│ ├── defaultFields.js
│ ├── index.js
│ └── parser.js
├── package.json
└── readme.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
node_modules
*.log
*.
================================================
FILE: bin/fontpath
================================================
#!/usr/bin/env node
var fs = require('fs');
var argv = require('optimist')
.usage('fontpath [options] path/to/FontFile.ttf')
.demand(1)
.alias('c', 'chars')
.describe('c', 'the character set: all, ascii, ascii-extended')
.default('c', 'ascii')
.alias('s', 'size')
.default('s', 64)
.describe('s', 'the font size in points')
.alias('r', 'resolution')
.describe('r', 'the resolution in DPI')
.default('r', 72)
.alias('o', 'output')
.describe('o', 'a file to save the data to')
.describe('commonJS', 'wrap with module.exports for a JS file')
.describe('ignoreKerning', 'ignore kerning')
.describe('ignorePath', 'ignore font outlines')
.describe('pretty', 'pretty-print the output')
.argv;
var parse = require('../lib/index.js');
fs.readFile(argv._[0], function(err, buffer) {
if (err)
throw err;
parse(buffer, {
output: argv.o,
commonJS: argv.commonJS,
prettyPrint: argv.pretty,
ignoreKerning: argv.ignoreKerning,
ignorePath: argv.ignorePath,
resolution: argv.resolution,
size: argv.size,
charcodes: argv.c,
});
});
================================================
FILE: lib/SimpleJson.js
================================================
//Exports to a minimal JSON format that is useful for web purposes
var fs = require('fs');
var pkg = require('../package.json');
var EXPORTER_NAME = "SimpleJson";
function SimpleJson() {
}
SimpleJson.prototype.export = function(fontInfo, options) {
var writer = options.output ? fs.createWriteStream(options.output) : process.stdout;
var objOut = {};
for (var k in fontInfo) {
if (k !== 'glyphs' && k !== 'kerning')
objOut[k] = fontInfo[k];
}
//For better minification, a list of arrays
//Format: [leftChar, rightChar, kerning]
objOut.kerning = [];
if (fontInfo.kerning) {
for (var i=0; i<fontInfo.kerning.length; i++) {
var kern = fontInfo.kerning[i];
objOut.kerning.push(
[ String.fromCharCode(kern.left),
String.fromCharCode(kern.right),
kern.value ]);
}
}
objOut.glyphs = {};
for (var i=0; i<fontInfo.glyphs.length; i++) {
var g = fontInfo.glyphs[i];
var glyphOut = {
xoff: g.metrics.horiAdvance,
width: g.metrics.width,
height: g.metrics.height,
hbx: g.metrics.horiBearingX,
hby: g.metrics.horiBearingY
};
if (g.outline)
glyphOut.path = g.outline || [];
objOut.glyphs[ String.fromCharCode(g.code) ] = glyphOut;
}
objOut.exporter = EXPORTER_NAME;
objOut.version = pkg.version;
var jsonOut = JSON.stringify(objOut, null, options.prettyPrint ? 2 : null);
if (options.commonJS) {
jsonOut = "module.exports = "+jsonOut+";";
}
writer.write(jsonOut);
}
SimpleJson.prototype.getGlyphOutline = function(ft, face, code) {
if (face.glyph.format !== ft.GLYPH_FORMAT_OUTLINE) {
// console.warn("Charcode", code, "("+String.fromCharCode(code)+") has no outline");
return [];
}
var data = [];
ft.Outline_Decompose(face, {
move_to: function(x, y) {
data.push(["m", x, y]);
},
line_to: function(x, y) {
data.push(["l", x, y]);
},
quad_to: function(cx, cy, x, y) {
data.push(["q", cx, cy, x, y]);
},
cubic_to: function(cx1, cy1, cx2, cy2, x, y) {
data.push(["c", cx1, cy1, cx2, cy2, x, y]);
},
});
return data;
}
//small decrease in filesize, worse to parse though.. worth it?
SimpleJson.prototype.getGlyphOutlineStr = function(ft, face, code) {
if (face.glyph.format !== ft.GLYPH_FORMAT_OUTLINE) {
// console.warn("Charcode", code, "("+String.fromCharCode(code)+") has no outline");
return [];
}
var data = "";
ft.Outline_Decompose(face, {
move_to: function(x, y) {
data += "m "+(Math.floor(x))+" "+(Math.floor(y))+" ";
},
line_to: function(x, y) {
data += "l "+(Math.floor(x))+" "+(Math.floor(y))+" ";
},
quad_to: function(cx, cy, x, y) {
data += "q "+(Math.floor(cx))+" "+(Math.floor(cy))+" "+(Math.floor(x))+" "+(Math.floor(y))+" ";
},
cubic_to: function(cx1, cy1, cx2, cy2, x, y) {
data += "c "+(Math.floor(cx1))+" "+(Math.floor(cy1))+" "+(Math.floor(cx2))+" "+(Math.floor(cy2))+" "+(Math.floor(x))+" "+(Math.floor(y))+" ";
},
});
return data.trim();
}
module.exports = SimpleJson;
================================================
FILE: lib/defaultFields.js
================================================
module.exports = [
'style_name', 'family_name', 'ascender',
'descender', 'height', 'underline_thickness',
'underline_position', 'units_per_EM',
'max_advance_width'
];
================================================
FILE: lib/index.js
================================================
var fs = require('fs');
var ft = require('freetype2');
var SimpleJson = require('./SimpleJson');
var defaultFields = require('./defaultFields');
function getAvailableCharacters(ft, face) {
var gindex = {},
charcode,
chars = [];
charcode = ft.Get_First_Char(face, gindex);
while (gindex.gindex !== 0) {
chars.push(charcode);
charcode = ft.Get_Next_Char(face, charcode, gindex);
}
return chars;
}
function basicASCII(extended) {
var codes = [];
for (var i=32; i<=126; i++)
codes.push( i );
if (extended) {
for (i=161; i<255; i++)
codes.push( i );
}
return codes;
}
function getKerning(ft, face, chars, available, kernMode) {
var kernings = [];
kernMode = kernMode || ft.KERNING_DEFAULT;
for (var i=0; i<chars.length; i++) {
var leftCode = chars[i];
var left = ft.Get_Char_Index(face, leftCode);
for (var j=0; j<chars.length; j++) {
var rightCode = chars[j];
var right = ft.Get_Char_Index(face, rightCode);
var kern = { x:0, y:0 };
var err = ft.Get_Kerning(face, left, right, kernMode, kern);
if (!err && kern.x !== 0) {
kernings.push({
left: leftCode,
right: rightCode,
value: kern.x
});
}
}
}
// console.log("Found", kernings.length, "kerning pairs");
return kernings;
}
//this tool is a bit of a mess. gotta clean 'er up..
function parse(buffer, options) {
options = options||{};
// Create a font face
var face = ft.New_Memory_Face(buffer, 0);
var available = getAvailableCharacters(ft, face);
// if ((face.face_flags & ft.FACE_FLAG_SCALABLE) !== ft.FACE_FLAG_SCALABLE)
// console.warn("Font is not scalable");
var codesToUse = options.charcodes;
if (options.charcodes === "all")
codesToUse = available;
else if (!codesToUse || codesToUse === "ascii")
codesToUse = basicASCII();
else if (codesToUse === "ascii-extended")
codesToUse = basicASCII(true);
var exporter = options.exporter || new SimpleJson();
var fontPtSize = options.size || 12;
var fontResolution = options.resolution || 72;
var ignoreKerning = options.ignoreKerning;
var ignorePath = options.ignorePath;
var exportFields = options.fields || defaultFields;
//if 'all' is specified, run the tool on the entire set
var charcodes = options.charcodes === "all"
? available
: codesToUse.filter(function(c) {
return available.indexOf(c) !== -1;
});
//Set the point size
ft.Set_Char_Size(face, fontPtSize * 64, fontPtSize * 64, fontResolution, fontResolution);
var dataObj = {};
dataObj.size = fontPtSize;
dataObj.resolution = fontResolution;
//copy contents..
for (var k in face) {
if (defaultFields.indexOf(k) !== -1)
dataObj[k] = face[k];
}
if (!ignoreKerning) {
//check if we have kerning in the font file
if ( (face.face_flags & ft.FACE_FLAG_KERNING) === ft.FACE_FLAG_KERNING ) {
dataObj.kerning = getKerning(ft, face, charcodes, available);
} else {
// console.warn("No kerning information in font file.");
dataObj.kerning = [];
}
}
dataObj.glyphs = [];
for (var i=0; i<charcodes.length; i++) {
var code = charcodes[i];
var gindex = ft.Get_Char_Index(face, code);
ft.Load_Glyph(face, gindex, ft.LOAD_NO_BITMAP);
var metrics = {};
for (var k in face.glyph.metrics) {
metrics[k] = face.glyph.metrics[k];
}
var glyph = {
code: charcodes[i],
metrics: metrics
};
if (!ignorePath) {
glyph.outline = exporter.getGlyphOutline(ft, face, code);
}
dataObj.glyphs.push(glyph);
}
exporter.export(dataObj, options);
}
module.exports = parse;
================================================
FILE: lib/parser.js
================================================
function Parser(buffer, options) {
}
Parser.Font = function() {
};
module.exports = parser
/*
Parser: parses TTF/OTF/WOFF/etc files into objects:
Data
type
version
scaled
family_name
style_name
size
style_flags
face_flags
ascender
descender
underline_thickness
underline_position
max_advance_width
width
height
glyphs
kerning
paths
bitmap //only if we have fontpath-bmfont
*/
================================================
FILE: package.json
================================================
{
"name": "fontpath",
"version": "0.0.6",
"description": "Generates path and kerning info from a font",
"main": "index.js",
"bin": {
"fontpath": "./bin/fontpath"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Matt DesLauriers",
"license": "MIT",
"dependencies": {
"freetype2": "mattdesl/node-freetype2#shapes",
"optimist": "^0.6.1"
},
"devDependencies": {},
"directories": {
"example": "examples"
},
"repository": {
"type": "git",
"url": "https://github.com/mattdesl/fontpath.git"
},
"keywords": [
"font",
"fonts",
"ttf",
"otf",
"woff",
"freetype",
"freetype2",
"vector",
"outline",
"decompose"
],
"bugs": {
"url": "https://github.com/mattdesl/fontpath/issues"
},
"homepage": "https://github.com/mattdesl/fontpath"
}
================================================
FILE: readme.md
================================================
# fontpath
[](http://github.com/badges/stability-badges)
A tool which generates paths and kerning data from a TTF/OTF/WOFF/etc font. The paths can then be decomposed into points, or rendered to a canvas, or triangulated.
The project is similar to [typeface.js](http://typeface.neocracy.org/) and [cufon](http://cufon.shoqolate.com/generate/). Both of those tools are very old, and were made before @font-face gained widespread support. This project has a few different goals in mind:
- Stronger focus on WebGL/animations/effects rather than trying to replace DOM text rendering
- NPM/node tooling, eventual integration with build tools
- decoupled modules, e.g. outline generator doesn't depend on rendering utils, glyph layout doesn't depend on canvas rendering
- rendering engine isn't tied to Canvas (or even the browser; e.g. you could use node-canvas)
- eventually, these tools could be used by a server to generate paths or hinted bitmap data for the client
- TTF, OTF, WOFF, and most other formats supported (FreeType2)
- font converter is an offline tool and fairly easy to modify (i.e. for a custom JSON/binary exporter)
- you can specify any charsets with the API (e.g. foreign and icon fonts)
- other stuff: hit detection on paths, advanced glyph/face metrics
# example
```fontpath myfont.ttf -o mfont.json --size 128```
The default size is 12 pt, but exporting with a higher font size will give you better resolution when rendering the path at large sizes. It's best to match the exported size to the final rendered size, as it will produce better rounding when scaled down.
# roadmap
This project is a heavy WIP. Some things I want to explore:
- Bitmap font rendering and atlas packing for Canvas/WebGL
- Basic support for styled/attributed text (italics, bold, color, etc)
- Maybe some tools for SDF rendering
- Better Node/CLI integration
New modules will be added to [text-modules](https://github.com/mattdesl/text-modules).
# demos
- [Triangulated text effect](http://mattdesl.github.io/fontpath-renderer/demo/tris.html) - a custom renderer using triangles
- [Custom steiner points](http://mattdesl.github.io/shape2d-triangulate/demo/glyph.html) - finer control over triangulation for creative effects
- [WebGL Path Rendering](http://mattdesl.github.io/fontpath-gl/demo/)
- [WebGL Triangulated Rendering](http://mattdesl.github.io/fontpath-gl/demo/wireframe.html)
- [Bitmap Fonts](http://mattdesl.github.io/gl-sprite-text/demo/demo.html)
- [Signed-Distance Field Bitmap Fonts](http://mattdesl.github.io/gl-sprite-text/demo/demo-sdf.html)
# modules
*Note:* New modules will be more generic and not specifically tied to "fontpath." See [text-modules](https://github.com/mattdesl/text-modules).
The framework is split into many small modules. Some of them aren't specific to fontpath, but are useful alongside it. You generally won't need to use all of them together; but instead, you'll pick and choose based on your particular application.
Most commonly, you might want to use a "renderer" which gives you a basic word-wrapper and glyph layout tools.
- [fontpath-canvas](https://github.com/mattdesl/fontpath-canvas) - a renderer using 2D Canvas and paths for fill/stroke
- [fontpath-gl](https://github.com/mattdesl/fontpath-gl) - a WebGL renderer using stackgl modules
- [gl-sprite-text](https://github.com/mattdesl/gl-sprite-text) - a WebGL renderer for [BMFont](http://www.angelcode.com/products/bmfont/) files that can also be used for signed-distance field text
Some other utilities that make up the ecosystem:
- [fontpath-simple-renderer](https://github.com/mattdesl/fontpath-simple-renderer) a generic renderer, useful if you need something more optimized
- [fontpath-wordwrap](https://github.com/mattdesl/fontpath-wordwrap) a basic word wrapper that supports `pre` and `nowrap` (for parity with CSS)
- [fontpath-util](https://github.com/mattdesl/fontpath-util) - point to pixel utilities
- [shape2d](https://github.com/mattdesl/shape2d) - Converts bezier/quadratic curves into points, with HTML5CanvasContext-like API
- [shape2d-triangulate](https://github.com/mattdesl/shape2d-triangulate) - triangulates a list of Shapes from shape2d, ideal for triangulating fontpath glyphs. uses poly2tri
- [fontpath-shape2d](https://github.com/mattdesl/fontpath-shape2d) - decomposes a fontpath JSON/JS glyph into points with shape2d
- [fontpath-test-fonts](https://github.com/mattdesl/fontpath-test-fonts) - some fonts that have already been exported to JSON, so you can easily pull them in with NPM
- [fontpath-vecmath](https://github.com/mattdesl/fontpath-vecmath) - vector/matrix utilities for font and glyph faces, built on [vecmath](https://github.com/mattdesl/vecmath)
- [point-util](https://github.com/mattdesl/point-util) - used by shape2d-triangulate, but includes a couple of handy features like `pointInPoly`
# license
MIT
gitextract_0tfz4ibk/ ├── .gitignore ├── bin/ │ └── fontpath ├── lib/ │ ├── SimpleJson.js │ ├── defaultFields.js │ ├── index.js │ └── parser.js ├── package.json └── readme.md
SYMBOL INDEX (6 symbols across 3 files)
FILE: lib/SimpleJson.js
function SimpleJson (line 7) | function SimpleJson() {
FILE: lib/index.js
function getAvailableCharacters (line 7) | function getAvailableCharacters(ft, face) {
function basicASCII (line 21) | function basicASCII(extended) {
function getKerning (line 32) | function getKerning(ft, face, chars, available, kernMode) {
function parse (line 60) | function parse(buffer, options) {
FILE: lib/parser.js
function Parser (line 1) | function Parser(buffer, options) {
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (15K chars).
[
{
"path": ".gitignore",
"chars": 22,
"preview": "node_modules\n*.log\n*.\n"
},
{
"path": "bin/fontpath",
"chars": 1074,
"preview": "#!/usr/bin/env node\n\nvar fs = require('fs');\nvar argv = require('optimist')\n\t\t.usage('fontpath [options] path/to/FontFil"
},
{
"path": "lib/SimpleJson.js",
"chars": 2946,
"preview": "//Exports to a minimal JSON format that is useful for web purposes\nvar fs = require('fs');\nvar pkg = require('../package"
},
{
"path": "lib/defaultFields.js",
"chars": 171,
"preview": "module.exports = [\n\t'style_name', 'family_name', 'ascender',\n\t'descender', 'height', 'underline_thickness',\n\t'underline_"
},
{
"path": "lib/index.js",
"chars": 3512,
"preview": "var fs = require('fs');\nvar ft = require('freetype2');\nvar SimpleJson = require('./SimpleJson');\n\nvar defaultFields = re"
},
{
"path": "lib/parser.js",
"chars": 476,
"preview": "function Parser(buffer, options) {\n\n}\n\nParser.Font = function() {\n\n};\n\n\n\n\nmodule.exports = parser\n\n\n\n\n/*\nParser: parses "
},
{
"path": "package.json",
"chars": 870,
"preview": "{\n \"name\": \"fontpath\",\n \"version\": \"0.0.6\",\n \"description\": \"Generates path and kerning info from a font\",\n \"main\": "
},
{
"path": "readme.md",
"chars": 4951,
"preview": "# fontpath\n\n[](http://github.com/badges/s"
}
]
About this extraction
This page contains the full source code of the mattdesl/fontpath GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 8 files (13.7 KB), approximately 4.2k tokens, and a symbol index with 6 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.