Babylon.Font

About

Generate text mesh for babylonjs using WASM, written in AssemblyScript.

Example

Installation

With cdn

https://cdn.jsdelivr.net/gh/ycw/babylon.font@{VERSION}/build/babylon.font.js

or npm

npm i ycw/babylon.font
npm i ycw/babylon.font#{VERSION_TAG}

Usage

import * as BABYLON from "babylonjs"
import * as opentype from "opentype.js"
import earcut from "earcut"
import { Compiler, Font, TextMeshBuilder } from "babylon.font";

(async function() {
  const compiler = await Compiler.Build();
  const font = await Font.Install("a.ttf", compiler, opentype);
  const builder = new TextMeshBuilder(BABYLON, earcut);
  const scene = ..;
  const mesh = builder.create({ font, text: "foo" }, scene);
})();

Docs

Compiler

// (1) auto-probe .wasm url
await Compiler.Build();

// (2) specify .wasm url
await Compiler.Build(wasmUrl);

The signature(2) is useful when using bundler / dev server :

// ex. obtain static asset url for ViteJS/Vite
import wasmUrl from "babylon.font/build/optimized.wasm?url";
const compiler = await Compiler.Build(wasmUrl);

Font

await Font.Install(fontUrl, compiler, opentype);
// fontUrl:  font(.otf/.ttf) url
// compiler: a Compiler instance
// opentype: the 'opentype.js' lib

Metrics


TextMeshBuilder

Construct a text mesh builder

new TextMeshBuilder(BABYLON, earcut);
// BABYLON: the 'babylonjs' lib
// earcut: the 'earcut' lib
builder.create({
  font, // Font instance
  text, // text
  size, // font size; default is 100
  ppc, // points per curve, [0, 255], default is 2
  eps, // decimation threshold, default is 0.001

  // plus `BABYLON.MeshBuilder.CreatePolygon` options
  depth,
  sideOrientation,
  faceColors,
  faceUV,
  backUVs,
  frontUVs,
  updatable,
}, scene);

ex. fallback

var mesh = builder.create(opt1, scene)
if (mesh === undefined) mesh = builder.create(opt2, scene) 

Thanks

MaxGraey - Helps with AssemblyScript/WASM optimizations

OpentypeJS - Read and write OpenType fonts using JavaScript.

Earcut - The fastest and smallest JavaScript polygon triangulation library for your WebGL apps

BabylonJS - A powerful, beautiful, simple, and open game and rendering engine packed into a friendly JavaScript framework.

AssemblyScript - Compiles a strict subset of TypeScript (basically JavaScript with types) to WebAssembly using Binaryen.

License

MIT