ycw/babylon.font example

https://forum.babylonjs.com/t/building-mesh-from-glyphs-in-real-time/7127/3

by Michael Prosser

HTML

<script src='https://rawcdn.githack.com/ycw/Babylon.Font/36e99d97360e6941d2ca17d2ac80350dbb28ed85/app/gen/lib/babylon.4.0.3.js'></script>

<script src='https://rawcdn.githack.com/ycw/Babylon.Font/36e99d97360e6941d2ca17d2ac80350dbb28ed85/app/gen/lib/earcut.min.2.2.1.js'></script>

<script src='https://rawcdn.githack.com/ycw/Babylon.Font/36e99d97360e6941d2ca17d2ac80350dbb28ed85/app/gen/lib/opentype.min.1.1.0.js'></script>

<script src='https://rawcdn.githack.com/ycw/Babylon.Font/36e99d97360e6941d2ca17d2ac80350dbb28ed85/dist/babylon.font.js'></script>

<canvas></canvas>

CSS

canvas {
  display: block;
  width: 100vw;
  height: 100vh;
}

html, body {
  padding: 0;
  margin: 0;
}

JavaScript

// ---- the url of compiler.wasm ----
const wasmUrl = 'https://rawcdn.githack.com/ycw/Babylon.Font/36e99d97360e6941d2ca17d2ac80350dbb28ed85/dist/compiler.wasm';

// ---- the url of font ----
const fontUrl = 'https://rawcdn.githack.com/ycw/Babylon.Font/36e99d97360e6941d2ca17d2ac80350dbb28ed85/app/gen/font/NotoSansMono-Thin.ttf';

(async function main() {

    // ( 'BF' is the namespace exposed from babylon.font.js )
    const compiler = await BF.Compiler.Build(wasmUrl);
    const font = await BF.Font.Install(fontUrl, compiler);
    
    // Create BabylonJS Env
    const canvas = document.querySelector('canvas');
    const option = { preserveDrawingBuffer: true, stencil: true };
    const engine = new BABYLON.Engine(canvas, true, option, true);
    const scene = new BABYLON.Scene(engine);
    engine.runRenderLoop(() => scene.render());
    
    // Setup Camera
    const cam = new BABYLON.ArcRotateCamera('',
        BABYLON.Tools.ToRadians(-90), BABYLON.Tools.ToRadians(45),
        100, new BABYLON.Vector3(), scene
    );
    cam.attachControl(scene.getEngine().getRenderingCanvas());
    
    // Create Shadow Light 
    const light0 = new BABYLON.DirectionalLight('light0',
        new BABYLON.Vector3(-1, -1, 0), scene
    );
    light0.intensity = 2;

    // Create Font Material
    const textMat = new BABYLON.StandardMaterial('text');
    textMat.specularColor.set(1, 1, 1);
    
    // Create Text Mesh
    
    const ch = 'BULLSHIT';
    const size = 100;
    const ppc = 24;
    const eps = 0.000000001;
    const shapes = BF.Font.Compile(font, ch, size, ppc, eps);
    
    const depth = 10;
    const sideOrientation = BABYLON.Mesh.DOUBLESIDE;
    const mesh = BF.Font.BuildMesh(shapes, { depth, sideOrientation });
    mesh.material = textMat;
})();