### Install text-shaper
Source: https://github.com/wiedymi/text-shaper/blob/main/README.md
Install the text-shaper package using npm or bun.
```bash
npm install text-shaper
# or
bun add text-shaper
```
--------------------------------
### BitmapBuilder: create Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Example showing how to create a new, empty BitmapBuilder with specified dimensions and pixel mode.
```typescript
const canvas = BitmapBuilder.create(100, 100, PixelMode.Gray);
```
--------------------------------
### BitmapBuilder: fromGradient Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Example demonstrating the creation of a BitmapBuilder with a linear gradient background.
```typescript
const gradientBg = BitmapBuilder.fromGradient(100, 100, {
type: "linear",
x0: 0, y0: 0,
x1: 100, y1: 100,
stops: [
{ offset: 0, color: [255, 0, 0, 255] },
{ offset: 1, color: [0, 0, 255, 255] }
]
});
```
--------------------------------
### Install TextShaper with Bun
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/getting-started.md
Install the text-shaper package using the Bun package manager.
```bash
bun add text-shaper
```
--------------------------------
### Basic Text Shaping Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/getting-started.md
A minimal example demonstrating how to load a font, create a text buffer, shape the text, and access the resulting glyph information and positions.
```typescript
import { Font, shape, UnicodeBuffer } from "text-shaper";
// Load a font
const font = await Font.fromFile("path/to/font.ttf");
// Create a buffer with text
const buffer = new UnicodeBuffer().addStr("Hello, world!");
// Shape the text
const result = shape(font, buffer);
// Access shaped glyphs
for (let i = 0; i < result.length; i++) {
const info = result.infos[i];
const pos = result.positions[i];
console.log({
glyphId: info.glyphId,
cluster: info.cluster,
xAdvance: pos.xAdvance,
yAdvance: pos.yAdvance,
xOffset: pos.xOffset,
yOffset: pos.yOffset,
});
}
```
--------------------------------
### Get Glyph Path Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Demonstrates how to retrieve the path commands for a specific glyph from a font. Requires importing Font and getGlyphPath.
```typescript
import { Font, getGlyphPath } from "typeshaper";
const font = await Font.fromFile("font.ttf");
const glyphId = font.glyphIdForChar("A");
const path = getGlyphPath(font, glyphId);
if (path) {
console.log(`Glyph has ${path.commands.length} commands`);
console.log(`Bounds:`, path.bounds);
}
```
--------------------------------
### BitmapBuilder: fromRasterizedGlyph Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Example demonstrating how to create a BitmapBuilder from a rasterized glyph and apply effects.
```typescript
const glyph = rasterizeGlyph(font, glyphId, options);
const builder = BitmapBuilder.fromRasterizedGlyph(glyph);
const rgba = builder.blur(3).toRGBA();
```
--------------------------------
### Variable Font Rendering Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Shows how to render text using a variable font by specifying font face properties like weight. Includes setup for font loading, shaping, and rendering to canvas.
```typescript
import {
Font,
Face,
UnicodeBuffer,
shape,
glyphBufferToShapedGlyphs,
renderShapedText
} from "typeshaper";
async function renderVariableText() {
const font = await Font.fromFile("variable.ttf");
// Create face with weight=700
const face = new Face(font, { wght: 700 });
const buffer = new UnicodeBuffer();
buffer.addStr("Variable");
const shaped = shape(face, buffer);
const glyphs = glyphBufferToShapedGlyphs(shaped);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (ctx) {
renderShapedText(ctx, font, glyphs, {
fontSize: 72,
x: 50,
y: 100
});
}
}
```
--------------------------------
### Complete Text Shaping Example with OpenType Features
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/features.md
A comprehensive example showcasing the integration of font loading, buffer creation, and the application of multiple OpenType features including ligatures, kerning, old-style figures, and small caps. It also includes rendering glyph information.
```typescript
import {
Font,
shape,
UnicodeBuffer,
standardLigatures,
discretionaryLigatures,
kerning,
oldstyleFigures,
smallCaps
} from "text-shaper";
const font = await Font.fromFile("font.ttf");
const buffer = new UnicodeBuffer()
.addStr("The Office: 1234")
.setScript("Latn")
.setLanguage("en");
const result = shape(font, buffer, {
features: [
standardLigatures(), // fi, fl ligatures
discretionaryLigatures(), // ct, st ligatures
kerning(), // spacing adjustments
oldstyleFigures(), // old-style numbers
smallCaps(), // small caps
]
});
// Render glyphs
for (let i = 0; i < result.length; i++) {
const info = result.infos[i];
const pos = result.positions[i];
console.log(`Glyph ${info.glyphId}: advance ${pos.xAdvance}`);
}
```
--------------------------------
### Install TextShaper with npm
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/getting-started.md
Install the text-shaper package using the npm package manager.
```bash
npm install text-shaper
```
--------------------------------
### Basic Bun Test Example
Source: https://github.com/wiedymi/text-shaper/blob/main/CLAUDE.md
A simple test case using Bun's built-in testing framework. This example verifies basic assertion functionality.
```typescript
import { test, expect } from "bun:test";
test("hello world", () => {
expect(1).toBe(1);
});
```
--------------------------------
### BitmapBuilder: fastBlur Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Example illustrating the use of `fastBlur` for efficient blurring of large radii, contrasting it with the standard `blur` method.
```typescript
// For large blur radii, fastBlur is more efficient
const blurred = glyph(font, glyphId)
?.rasterizeAuto({ padding: 50 })
.fastBlur(20) // Much faster than blur(20)
.toRGBA();
```
--------------------------------
### Vue Script Setup for Playground Components
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/playground/index.md
Imports necessary Vue components and defines reactive state for font loading and handling font data. This setup is used to manage the application's state and component interactions within the playground.
```javascript
import { ref } from 'vue'
import FontPicker from '../.vitepress/components/FontPicker.vue'
import ShapingPlayground from '../.vitepress/components/ShapingPlayground.vue'
import VariableFontPlayground from '../.vitepress/components/VariableFontPlayground.vue'
import GlyphInspector from '../.vitepress/components/GlyphInspector.vue'
import RasterPreview from '../.vitepress/components/RasterPreview.vue'
import SdfPreview from '../.vitepress/components/SdfPreview.vue'
import MsdfPreview from '../.vitepress/components/MsdfPreview.vue'
import SyntheticEffects from '../.vitepress/components/SyntheticEffects.vue'
import EffectsPreview from '../.vitepress/components/EffectsPreview.vue'
import TransformPreview from '../.vitepress/components/TransformPreview.vue'
import StrokePreview from '../.vitepress/components/StrokePreview.vue'
const font = ref(null)
const fontName = ref('')
function handleFontLoaded(loadedFont, name) {
font.value = loadedFont
fontName.value = name
}
```
--------------------------------
### Quick Start: Builder Style
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Demonstrates the builder pattern for composing glyph transformations and rendering using method chaining.
```typescript
import { glyph } from "text-shaper";
const rgba = glyph(font, glyphId)
?.scale(2)
.rotateDeg(15)
.rasterizeAuto({ padding: 2 })
.blur(5)
.toRGBA();
```
--------------------------------
### Complete Shaping Example for Devanagari Text
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/basic-usage.md
Demonstrates configuring a UnicodeBuffer for Devanagari and performing shaping.
```typescript
const buffer = new UnicodeBuffer()
.addStr("नमस्ते")
.setDirection(Direction.LTR)
.setScript("Deva")
.setLanguage("hi");
const result = shape(font, buffer);
```
--------------------------------
### Control Path Filling with Fill Rules
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/rasterization.md
Control how overlapping paths are filled using different fill rules. This example shows how to get a fill rule from flags, with options for NonZero and EvenOdd.
```typescript
import { FillRule, getFillRuleFromFlags } from "text-shaper";
// Get fill rule from path flags
const rule = getFillRuleFromFlags(path, FillRule.NonZero);
// FillRule.NonZero - Non-zero winding (default)
// FillRule.EvenOdd - Even-odd alternating fill
```
--------------------------------
### Complete Shaping Example for Arabic Text
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/basic-usage.md
Demonstrates configuring a UnicodeBuffer for Arabic and performing shaping.
```typescript
const buffer = new UnicodeBuffer()
.addStr("مرحبا بك")
.setDirection(Direction.RTL)
.setScript("Arab")
.setLanguage("ar");
const result = shape(font, buffer);
```
--------------------------------
### Complete Shaping Example for English Text
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/basic-usage.md
Demonstrates loading a font, configuring a UnicodeBuffer for English, and performing shaping.
```typescript
import { Font, shape, UnicodeBuffer, Direction } from "text-shaper";
const font = await Font.fromFile("font.ttf");
const buffer = new UnicodeBuffer()
.addStr("Hello, World!")
.setDirection(Direction.LTR)
.setScript("Latn")
.setLanguage("en");
const result = shape(font, buffer);
```
--------------------------------
### Complete Text Shaping Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/advanced/custom-features.md
A comprehensive example demonstrating the use of `shape`, `combineFeatures`, and various typography features like small caps, oldstyle figures, and discretionary ligatures.
```typescript
import {
shape,
combineFeatures,
feature,
allSmallCaps,
oldstyleFigures,
discretionaryLigatures,
kerning
} from "text-shaper";
const result = shape(font, buffer, {
script: "latn",
language: null,
direction: "ltr",
features: combineFeatures(
// Disable defaults
kerning(false),
// Enable typography features
allSmallCaps(),
oldstyleFigures(),
discretionaryLigatures(),
// Custom stylistic set
feature("ss03")
)
});
```
--------------------------------
### Quick Start: Pipe Style
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Demonstrates the pipe pattern for functional composition of glyph transformations and rendering using curried operators.
```typescript
import { pipe, $scale, $rotate, $rasterize, $blur, $toRGBA, getGlyphPath } from "text-shaper";
const rgba = pipe(
getGlyphPath(font, glyphId),
$scale(2, 2),
$rotate(Math.PI / 4),
$rasterize({ width: 100, height: 100 }),
$blur(5),
$toRGBA
);
```
--------------------------------
### Complete Rendering Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Demonstrates a full workflow from loading a font, shaping text, and rendering it to both a canvas element and generating SVG output. Includes necessary imports and async function structure.
```typescript
import {
Font,
UnicodeBuffer,
shape,
glyphBufferToShapedGlyphs,
renderShapedText,
shapedTextToSVG
} from "typeshaper";
async function renderText() {
// Load font
const font = await Font.fromFile("font.ttf");
// Create buffer and add text
const buffer = new UnicodeBuffer();
buffer.addStr("Hello, TypeShaper!");
// Shape the text
const shaped = shape(font, buffer);
const glyphs = glyphBufferToShapedGlyphs(shaped);
// Render to Canvas
const canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 200;
const ctx = canvas.getContext("2d");
if (ctx) {
renderShapedText(ctx, font, glyphs, {
fontSize: 48,
x: 50,
y: 100,
fill: "navy"
});
}
// Or get as SVG
const svg = shapedTextToSVG(font, glyphs, {
fontSize: 48,
fill: "navy"
});
document.body.appendChild(canvas);
document.body.innerHTML += svg;
}
renderText();
```
--------------------------------
### Enable Standard Ligatures
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/shaping.md
Example of using the `standardLigatures` helper to enable standard ligatures during shaping.
```typescript
import { standardLigatures, discretionaryLigatures } from "typeshaper";
const shaped = shape(font, buffer, {
features: standardLigatures(true) // Enable standard ligatures
});
```
--------------------------------
### Example Usage of Pipe with Path Operators
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Demonstrates how to use the pipe function with path operators like $scale, $rasterizeAuto, and $toRGBA to process a glyph path.
```typescript
const path = $fromGlyph(font, glyphId);
if (path) {
const rgba = pipe(path, $scale(2), $rasterizeAuto(), $toRGBA);
}
```
--------------------------------
### Manual Shape Plan Creation
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/advanced/shape-plan.md
Provides an example of manually creating a shape plan using `createShapePlan` without relying on TextShaper's automatic caching mechanism.
```typescript
import { createShapePlan } from "text-shaper/shaper/shape-plan";
const plan = createShapePlan(
font,
"latn", // script
null, // language (null = default)
"ltr", // direction
[
{ tag: tag("liga"), enabled: true },
{ tag: tag("kern"), enabled: true }
],
null // axis coords (null = no variation)
);
// plan.gsubLookups and plan.gposLookups contain the lookups
```
--------------------------------
### Dynamic Typography Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/variable-fonts.md
Implement dynamic typography by creating a function to shape text at different weights and adjusting font properties like weight and optical size based on font size.
```typescript
import { Font, Face, UnicodeBuffer, shape } from "text-shaper";
const font = await Font.fromFile("inter-variable.ttf");
// Function to shape text at different weights
function shapeAtWeight(text: string, weight: number) {
const face = new Face(font, { wght: weight });
const buffer = new UnicodeBuffer().addStr(text);
return shape(face, buffer);
}
// Generate headings at different weights
const heading1 = shapeAtWeight("Main Title", 800);
const heading2 = shapeAtWeight("Subtitle", 600);
const body = shapeAtWeight("Body text", 400);
// Responsive typography: adjust weight based on size
function getOptimalWeight(fontSize: number): number {
// Lighter weights for larger sizes
if (fontSize >= 48) return 500;
if (fontSize >= 24) return 600;
return 400;
}
const dynamicFace = new Face(font, {
wght: getOptimalWeight(72),
opsz: 72 // optical size matches font size
});
```
--------------------------------
### Convert Contour to Path Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Converts TrueType contours obtained from a font into a series of path commands.
```typescript
const contours = font.getGlyphContours(glyphId);
if (contours) {
for (const contour of contours) {
const commands = contourToPath(contour);
// Process commands
}
}
```
--------------------------------
### Generate Glyph SVG Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Creates a complete SVG element for a glyph, allowing customization of font size and fill color.
```typescript
const svg = glyphToSVG(font, glyphId, {
fontSize: 100,
fill: "black"
});
console.log(svg);
//
//
//
```
--------------------------------
### Enable Oldstyle and Tabular Figures
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/shaping.md
Example of combining `oldstyleFigures` and `tabularFigures` helpers to enable both number styles.
```typescript
import { oldstyleFigures, tabularFigures } from "typeshaper";
const shaped = shape(font, buffer, {
features: [...oldstyleFigures(true), ...tabularFigures(true)]
});
```
--------------------------------
### Path Source Operator
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
An operator to get a GlyphPath from a font and glyph ID. This is the starting point for path manipulation.
```typescript
$fromGlyph(font: Font, glyphId: GlyphId): GlyphPath | null
```
--------------------------------
### Get Glyph Path with Variation Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Retrieves path commands for a glyph, applying variable font variations using normalized axis coordinates.
```typescript
const coords = [0.5, 0]; // Normalized coordinates
const path = getGlyphPathWithVariation(font, glyphId, coords);
```
--------------------------------
### Low-Level Path Rasterization
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/rasterization.md
Rasterize arbitrary paths using the low-level rasterization function. This example shows how to set up width, height, scale, and offsets for rasterization.
```typescript
import { rasterizePath, getGlyphPath } from "text-shaper";
const path = getGlyphPath(font, glyphId);
const scale = 48 / font.unitsPerEm;
const bitmap = rasterizePath(path, {
width: 64,
height: 64,
scale,
offsetX: 0,
offsetY: 48, // baseline offset
flipY: true,
pixelMode: PixelMode.Gray,
});
```
--------------------------------
### BitmapBuilder: create
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Creates a new, empty BitmapBuilder with specified dimensions and pixel mode. Use this to start building a bitmap from scratch.
```typescript
static create(width: number, height: number, pixelMode?: PixelMode): BitmapBuilder
```
--------------------------------
### Bun Server with HTML Imports
Source: https://github.com/wiedymi/text-shaper/blob/main/CLAUDE.md
This snippet demonstrates how to set up a Bun server that serves an HTML file. It also includes optional websocket support and development hot module replacement.
```typescript
import index from "./index.html"
Bun.serve({
routes: {
"/": index,
"/api/users/:id": {
GET: (req) => {
return new Response(JSON.stringify({ id: req.params.id }));
},
},
},
// optional websocket support
websocket: {
open: (ws) => {
ws.send("Hello, world!");
},
message: (ws, message) => {
ws.send(message);
},
close: (ws) => {
// handle close
}
},
development: {
hmr: true,
console: true,
}
})
```
--------------------------------
### Convert Path to SVG Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Generates an SVG path data string from GlyphPath commands. Supports options for flipping the Y-axis and scaling.
```typescript
const path = getGlyphPath(font, glyphId);
if (path) {
const svgPath = pathToSVG(path, { flipY: true, scale: 1 });
console.log(``);
}
```
--------------------------------
### Running Bun Development Server
Source: https://github.com/wiedymi/text-shaper/blob/main/CLAUDE.md
Command to run the main server file with hot module replacement enabled.
```sh
bun --hot ./index.ts
```
--------------------------------
### Convert Path to SVG with 3D Matrix Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Applies a 3x3 matrix, including perspective transformations, to glyph path coordinates for SVG output.
```typescript
const perspective: Matrix3x3 = [
[0.1, 0, 100],
[0, 0.1, 100],
[0.0001, 0, 1] // Slight perspective effect
];
const svgPath = pathToSVGWithMatrix3D(path, perspective);
```
--------------------------------
### createHintingEngine
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/raster.md
Initializes and creates a TrueType hinting engine with configurable parameters for stack, storage, and CVT values.
```APIDOC
## createHintingEngine
### Description
Create a TrueType hinting engine.
### Method Signature
```typescript
function createHintingEngine(
unitsPerEM: number,
maxStack?: number,
maxStorage?: number,
maxFDefs?: number,
maxTwilightPoints?: number,
cvtValues?: Int32Array
): HintingEngine
```
```
--------------------------------
### Convert Path to SVG with 2D Matrix Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Applies a 2D affine transformation matrix to glyph path coordinates before converting to an SVG path string. Requires importing transformation functions.
```typescript
import { getGlyphPath, pathToSVGWithMatrix, rotate2D, scale2D, multiply2D } from "typeshaper";
const path = getGlyphPath(font, glyphId);
if (path) {
const matrix = multiply2D(rotate2D(Math.PI / 4), scale2D(0.1, 0.1));
const svgPath = pathToSVGWithMatrix(path, matrix);
console.log(``);
}
```
--------------------------------
### Enable Small Caps
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/shaping.md
Demonstrates using the `smallCaps` helper to enable small caps.
```typescript
import { smallCaps } from "typeshaper";
const shaped = shape(font, buffer, {
features: smallCaps(true)
});
```
--------------------------------
### Case Conversion Functions
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/unicode.md
Provides examples of converting text to uppercase, lowercase, and title case using the library's functions. These functions correctly handle Unicode characters.
```typescript
import { toUpperCase, toLowerCase, toTitleCase } from "text-shaper";
const upper = toUpperCase("hello".split("").map(c => c.codePointAt(0)));
const lower = toLowerCase("HELLO".split("").map(c => c.codePointAt(0)));
const title = toTitleCase("hello world".split("").map(c => c.codePointAt(0)));
```
--------------------------------
### Font.advanceWidth
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/font.md
Gets the horizontal advance width for a specified glyph ID.
```APIDOC
## Font.advanceWidth
### Description
Gets the advance width for a glyph.
### Method
Instance method of the Font class.
### Parameters
- **glyphId** (GlyphId) - The ID of the glyph.
### Returns
- **number** - The advance width of the glyph.
```
--------------------------------
### Basic HTML Structure for Bun Frontend
Source: https://github.com/wiedymi/text-shaper/blob/main/CLAUDE.md
A simple HTML file that imports a frontend script. Bun's bundler will automatically transpile and bundle the imported script.
```html
Hello, world!
```
--------------------------------
### Get Clusters
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/buffer.md
Retrieves an array of cluster numbers associated with the glyphs in the buffer.
```typescript
buffer.clusters();
```
--------------------------------
### Basic Glyph Rendering (Simple and Blurred)
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Demonstrates simple glyph rendering and applying blur effects after scaling and rasterization.
```typescript
import { glyph } from "text-shaper";
// Simple: glyph -> scale -> rasterize -> RGBA
const rgba = glyph(font, glyphId)
?.scale(2)
.rasterizeAuto({ padding: 2 })
.toRGBA();
// With rotation and blur
const blurred = glyph(font, glyphId)
?.scale(2)
.rotateDeg(15)
.rasterizeAuto({ padding: 10 })
.blur(3)
.toRGBA();
```
--------------------------------
### Get Glyph IDs
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/buffer.md
Retrieves an array of glyph IDs present in the buffer.
```typescript
buffer.glyphIds();
```
--------------------------------
### Texture Atlas Generation for GPU
Source: https://github.com/wiedymi/text-shaper/blob/main/README.md
Build texture atlases for efficient GPU rendering using WebGL. Supports building from glyph IDs, strings, or using MSDF for scalable text. Includes functions to convert atlases to RGBA and get glyph UV coordinates.
```typescript
import {
Font, buildAtlas, buildStringAtlas, buildMsdfAtlas,
atlasToRGBA, getGlyphUV, PixelMode
} from "text-shaper";
// Build atlas from glyph IDs
const atlas = buildAtlas(font, glyphIds, {
fontSize: 32,
padding: 2,
pixelMode: PixelMode.Gray,
});
// Build atlas from string (auto-extracts unique glyphs)
const textAtlas = buildStringAtlas(font, "Hello World!", {
fontSize: 48,
padding: 1,
});
// Convert to RGBA for WebGL texture
const rgba = atlasToRGBA(atlas);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, atlas.width, atlas.height,
0, gl.RGBA, gl.UNSIGNED_BYTE, rgba);
// Get UV coordinates for rendering
const uv = getGlyphUV(atlas, glyphId);
// uv = { u0, v0, u1, v1, ... }
// MSDF atlas for scalable GPU text
const msdfAtlas = buildMsdfAtlas(font, glyphIds, {
fontSize: 32,
spread: 4,
});
```
--------------------------------
### Font.leftSideBearing
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/font.md
Gets the left side bearing value for a specified glyph ID.
```APIDOC
## Font.leftSideBearing
### Description
Gets the left side bearing for a glyph.
### Method
Instance method of the Font class.
### Parameters
- **glyphId** (GlyphId) - The ID of the glyph.
### Returns
- **number** - The left side bearing of the glyph.
```
--------------------------------
### Create Hinting Engine
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/raster.md
Initializes and creates a TrueType hinting engine. Allows configuration of stack, storage, and CVT values.
```typescript
function createHintingEngine(
unitsPerEM: number,
maxStack?: number,
maxStorage?: number,
maxFDefs?: number,
maxTwilightPoints?: number,
cvtValues?: Int32Array
): HintingEngine
```
--------------------------------
### GlyphBuffer.removeRange
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/buffer.md
Removes a range of glyphs from the GlyphBuffer, specified by start and end indices.
```APIDOC
## GlyphBuffer.removeRange
### Description
Removes glyphs within a specified range.
### Method
```typescript
removeRange(start: number, end: number): void
```
### Parameters
* **start** (number) - Required - The starting index of the range (inclusive).
* **end** (number) - Required - The ending index of the range (exclusive).
```
--------------------------------
### Get Glyph ID for Character
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/font.md
Retrieves the glyph ID for a given character string.
```typescript
const glyphId = font.glyphIdForChar("A");
```
--------------------------------
### Inspect Shape Plan Details
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/advanced/shape-plan.md
Create a shape plan and log its script, language, direction, and the number of GSUB/GPOS lookups. Useful for understanding font behavior.
```typescript
const plan = createShapePlan(font, "arab", "ARA", "rtl");
console.log("Script:", tagToString(plan.script));
console.log("Language:", plan.language ? tagToString(plan.language) : "default");
console.log("Direction:", plan.direction);
console.log("GSUB lookups:", plan.gsubLookups.length);
console.log("GPOS lookups:", plan.gposLookups.length);
for (const { index, lookup } of plan.gsubLookups) {
console.log(` Lookup ${index}: type ${lookup.type}, ${lookup.subtables.length} subtables`);
}
```
--------------------------------
### Get Glyph ID for Codepoint
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/font.md
Retrieves the glyph ID associated with a given Unicode codepoint.
```typescript
const glyphId = font.glyphId(0x0041); // 'A'
```
--------------------------------
### Add String to UnicodeBuffer
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/buffer.md
Append a string to the UnicodeBuffer. Optionally specify the starting cluster index.
```typescript
buffer.addStr("Hello World");
```
--------------------------------
### Load CVT Program
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/raster.md
Loads and executes the CVT program (prep) for a given hinting engine.
```typescript
function loadCVTProgram(engine: HintingEngine, prep: Uint8Array): void
```
--------------------------------
### Get Glyph UV Coordinates
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Retrieves the UV coordinates for a specific glyph from an atlas. Useful for rendering.
```typescript
// Get UV coordinates for rendering
const uv = getGlyphUV(atlas, glyphId);
// { u0, v0, u1, v1 }
```
--------------------------------
### GlyphBuffer.initFromInfos
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/buffer.md
Initializes a GlyphBuffer from an array of GlyphInfo objects, setting positions to zero.
```APIDOC
## GlyphBuffer.initFromInfos
### Description
Initializes the buffer from glyph infos (positions zeroed).
### Method
```typescript
initFromInfos(infos: GlyphInfo[]): void
```
### Parameters
* **infos** (GlyphInfo[]) - Required - An array of GlyphInfo objects.
```
--------------------------------
### Get Path Bounds
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/raster.md
Calculates the pixel bounds of a scaled glyph path. Can optionally flip the Y-axis.
```typescript
function getPathBounds(
path: GlyphPath,
scale: number,
flipY?: boolean
): { minX: number; minY: number; maxX: number; maxY: number } | null
```
--------------------------------
### Font Loading in Browser
Source: https://github.com/wiedymi/text-shaper/blob/main/README.md
Demonstrates how to load font data from various sources in a browser environment.
```APIDOC
## Browser Usage
### Description
Examples of loading font data from URLs or File inputs using the `Font.load` method in a browser.
### Usage
- `Font.load(fontData: ArrayBuffer): Font` - Loads a font from an ArrayBuffer, which can be obtained from fetching a font file via URL or reading a File object.
```
--------------------------------
### Get Glyph Contours with Variation
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/tables.md
Retrieve glyph contours adjusted by variation coordinates from the Gvar table.
```typescript
const contours = font.getGlyphContoursWithVariation(glyphId, normalizedCoords);
```
--------------------------------
### Get Legacy Kerning Value
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/tables.md
Retrieve the kerning value between two glyphs from the legacy Kern table.
```typescript
import { getKernValue } from "typeshaper";
const kern = getKernValue(font.kern, glyph1, glyph2);
```
--------------------------------
### Reverse Glyph Range
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/buffer.md
Reverse the order of glyphs within a specified range [start, end) in the GlyphBuffer.
```typescript
reverseRange(start: number, end: number): void;
```
--------------------------------
### loadCVTProgram
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/raster.md
Loads and executes the CVT program (prep) for a given hinting engine.
```APIDOC
## loadCVTProgram
### Description
Load and execute CVT program (prep).
### Method Signature
```typescript
function loadCVTProgram(engine: HintingEngine, prep: Uint8Array): void
```
```
--------------------------------
### bitmap()
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Wraps an existing Bitmap in a BitmapBuilder, enabling fluent operations. This is an entry point for the fluent API.
```APIDOC
## bitmap()
### Description
Wrap an existing `Bitmap` in a `BitmapBuilder`.
### Signature
```typescript
function bitmap(b: Bitmap): BitmapBuilder
```
### Example
```typescript
const existingBitmap = rasterizePath(path, options);
const rgba = bitmap(existingBitmap).blur(5).toRGBA();
```
```
--------------------------------
### Checking Font Support for GSUB/GPOS Tables
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/features.md
Demonstrates how to verify if a font supports OpenType substitution (GSUB) and positioning (GPOS) tables using the `hasTable()` method. This is crucial for understanding a font's capabilities.
```typescript
const font = await Font.fromFile("font.ttf");
// Check if font has GSUB or GPOS tables
const hasGSUB = font.hasTable("GSUB");
const hasGPOS = font.hasTable("GPOS");
console.log(`Font supports substitution: ${hasGSUB}`);
console.log(`Font supports positioning: ${hasGPOS}`);
```
--------------------------------
### Get Total Advance Metrics
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/buffer.md
Retrieves the total advance width and height of the buffer. Useful for layout calculations.
```typescript
const advance = buffer.getTotalAdvance();
console.log(`Width: ${advance.x}, Height: ${advance.y}`);
```
--------------------------------
### path()
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Wraps an existing GlyphPath in a PathBuilder, allowing fluent transformations. This is an entry point for the fluent API.
```APIDOC
## path()
### Description
Wrap an existing `GlyphPath` in a `PathBuilder`.
### Signature
```typescript
function path(p: GlyphPath): PathBuilder
```
### Example
```typescript
const existingPath = getGlyphPath(font, glyphId);
if (existingPath) {
const rgba = path(existingPath).scale(2).rasterizeAuto().toRGBA();
}
```
```
--------------------------------
### Remove Glyph Range
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/buffer.md
Delete a range of glyphs from the GlyphBuffer, specified by start and end indices (exclusive of end).
```typescript
removeRange(start: number, end: number): void;
```
--------------------------------
### Apply Hinting to Glyph Path
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/rendering.md
Generates a glyph path with hinting applied, useful for improving rendering at small sizes. Supports manual control over hinting and ppem.
```typescript
// Most rasterizers apply hinting automatically
// For manual control:
const path = getGlyphPath(font, glyphId, {
hinting: true,
ppem: 16 // pixels per em (font size)
});
```
--------------------------------
### interpolateGradient
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/raster.md
Get interpolated color at position in gradient. Computes the RGBA color at pixel coordinates (x, y) within the gradient.
```APIDOC
## interpolateGradient
### Description
Get interpolated color at position in gradient. Computes the RGBA color at pixel coordinates `(x, y)` within the gradient. For linear gradients, projects the point onto the gradient line. For radial gradients, computes distance from center. Clamps to [0,1] range and interpolates between color stops.
### Method
(Function Signature)
### Parameters
- **gradient** (Gradient) - The gradient definition.
- **x** (number) - The x-coordinate.
- **y** (number) - The y-coordinate.
### Response
Array - An array representing the RGBA color [R, G, B, A] at the specified position.
```
--------------------------------
### Fluent Module Composition Styles
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/advanced/architecture.md
Demonstrates the two composition styles offered by the fluent module: builder pattern with method chaining and pipe pattern with functional composition.
```typescript
// Builder style
const rgba = glyph(font, glyphId)
?.scale(2)
.rasterizeAuto()
.blur(5)
.toRGBA();
// Pipe style
const rgba = pipe(
getGlyphPath(font, glyphId),
$scale(2),
$rasterizeAuto(),
$blur(5),
$toRGBA
);
```
--------------------------------
### Get Fill Rule from Flags
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/raster.md
Determines the fill rule from a glyph path's flags. A default rule can be provided.
```typescript
function getFillRuleFromFlags(
path: GlyphPath | null | undefined,
defaultRule?: FillRule
): FillRule
```
--------------------------------
### Get Font Metrics
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/guide/rendering.md
Access font metrics like unitsPerEm, ascender, descender, and lineGap to calculate line height.
```typescript
// Global font metrics
const unitsPerEm = font.head.unitsPerEm; // typically 1000 or 2048
const ascender = font.hhea.ascender; // height above baseline
const descender = font.hhea.descender; // depth below baseline (negative)
const lineGap = font.hhea.lineGap; // spacing between lines
// Calculate line height in pixels
const fontSize = 48;
const lineHeight = ((ascender - descender + lineGap) / unitsPerEm) * fontSize;
console.log(`Line height: ${lineHeight}px`);
```
--------------------------------
### createShapePlan()
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/shaping.md
Manually create a shape plan. This function is usually not needed as `shape()` handles plan creation internally.
```APIDOC
## createShapePlan()
### Description
Manually create a shape plan. Plans determine which lookups to apply during shaping and are cached for performance. This function is usually not needed, as the `shape()` function handles plan creation internally.
### Function Signature
```typescript
function createShapePlan(
font: Font,
script: string,
language: string | null,
direction: "ltr" | "rtl",
features: ShapeFeature[],
axisCoords: number[] | null
): ShapePlan
```
### Parameters
- `font` (Font) - The font to create the plan for.
- `script` (string) - The script tag (e.g., "arab", "latn").
- `language` (string | null) - The language tag (BCP 47, e.g., "en", "ar").
- `direction` ("ltr" | "rtl") - The text direction.
- `features` (ShapeFeature[]) - An array of OpenType features to enable/disable.
- `axisCoords` (number[] | null) - Coordinates for variable fonts.
```
--------------------------------
### BitmapBuilder: fromBitmap
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Creates a BitmapBuilder instance from an existing Bitmap object. This is the starting point for manipulating existing bitmap data.
```typescript
static fromBitmap(bitmap: Bitmap): BitmapBuilder
```
--------------------------------
### Table Access Pattern
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/tables.md
Demonstrates the lazy loading and caching mechanism for accessing font tables, along with checking for table presence.
```APIDOC
## Table Access Pattern
### Description
Illustrates the lazy loading and caching behavior for font tables. Tables are parsed on first access and cached for subsequent use. Also shows how to check for the presence of a table.
### Usage
```typescript
// Table is parsed on first access
const gdef = font.gdef; // Parses GDEF table
// Subsequent accesses use cached value
const gdef2 = font.gdef; // Returns cached table
// Check for table presence
if (font.hasTable(Tags.GSUB)) {
const gsub = font.gsub;
}
```
```
--------------------------------
### Debug GSUB Lookups and Features
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/advanced/shape-plan.md
Create a shape plan and log detailed information about each GSUB lookup, including its type and associated features.
```typescript
const plan = createShapePlan(font, "arab", null, "rtl");
console.log("GSUB lookups:");
for (const { index, lookup } of plan.gsubLookups) {
const features = getLookupsFeatures(font.gsub, index);
console.log(` ${index}: ${lookup.type} (features: ${features.join(", ")})`);
}
```
--------------------------------
### Add Codepoints to UnicodeBuffer
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/buffer.md
Add an array of Unicode codepoints directly to the buffer. Optionally specify the starting cluster index.
```typescript
buffer.addCodepoints([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
```
--------------------------------
### Load Font Program
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/raster.md
Loads and executes the font program (fpgm) for a given hinting engine.
```typescript
function loadFontProgram(engine: HintingEngine, fpgm: Uint8Array): void
```
--------------------------------
### Convert 2D Matrix to SVG Transform Attribute Example
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/rendering.md
Generates an SVG 'transform' attribute string from a 2D affine matrix.
```typescript
const matrix = multiply2D(rotate2D(0.5), scale2D(2, 2));
const attr = matrixToSVGTransform(matrix);
// "matrix(1.755 0.958 -0.958 1.755 0 0)"
console.log(``);
```
--------------------------------
### Face Class Constructor
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/font.md
Creates a new Face instance, representing a specific font instance with optional variation settings. This is useful for working with variable fonts.
```APIDOC
## new Face(font: Font, variations?: Record | Variation[])
### Description
Create a face with optional variation settings.
### Parameters
- **font** (Font) - The font object to create the face from.
- **variations** (Record | Variation[]) - Optional. An object or array specifying the variation axis values.
### Request Example
```typescript
const face = new Face(font, { wght: 700, wdth: 100 });
```
```
--------------------------------
### BitmapBuilder Methods
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Methods for resizing, padding, and compositing bitmaps.
```APIDOC
## resizeBilinear()
### Description
Resize with bilinear interpolation.
### Method
(Implicitly called on BitmapBuilder instance)
### Parameters
- **width** (number) - Required - The target width.
- **height** (number) - Required - The target height.
### Returns
BitmapBuilder - A new BitmapBuilder instance with the resized bitmap.
```
```APIDOC
## pad()
### Description
Pad bitmap with empty space.
### Method
(Implicitly called on BitmapBuilder instance)
### Parameters
Overloads:
1. **left** (number) - Required - Padding for the left side.
**top** (number) - Required - Padding for the top side.
**right** (number) - Required - Padding for the right side.
**bottom** (number) - Required - Padding for the bottom side.
2. **all** (number) - Required - Padding for all sides.
### Returns
BitmapBuilder - A new BitmapBuilder instance with padded bitmap.
```
```APIDOC
## blend()
### Description
Alpha blend another bitmap at a specified position.
### Method
(Implicitly called on BitmapBuilder instance)
### Parameters
- **other** (BitmapBuilder | Bitmap) - Required - The bitmap to blend.
- **x** (number) - Required - The x-coordinate for blending.
- **y** (number) - Required - The y-coordinate for blending.
- **opacity** (number) - Optional - The opacity of the blend.
### Returns
BitmapBuilder - A new BitmapBuilder instance with the blended bitmap.
```
```APIDOC
## composite()
### Description
Composite using Porter-Duff "over" operation.
### Method
(Implicitly called on BitmapBuilder instance)
### Parameters
- **other** (BitmapBuilder | Bitmap) - Required - The bitmap to composite.
- **x** (number) - Optional - The x-coordinate for compositing.
- **y** (number) - Optional - The y-coordinate for compositing.
### Returns
BitmapBuilder - A new BitmapBuilder instance with the composited bitmap.
```
```APIDOC
## add()
### Description
Additive blend.
### Method
(Implicitly called on BitmapBuilder instance)
### Parameters
- **other** (BitmapBuilder | Bitmap) - Required - The bitmap to add.
- **x** (number) - Optional - The x-coordinate for blending.
- **y** (number) - Optional - The y-coordinate for blending.
### Returns
BitmapBuilder - A new BitmapBuilder instance with the added bitmap.
```
```APIDOC
## subtract()
### Description
Subtractive blend.
### Method
(Implicitly called on BitmapBuilder instance)
### Parameters
- **other** (BitmapBuilder | Bitmap) - Required - The bitmap to subtract.
- **x** (number) - Optional - The x-coordinate for blending.
- **y** (number) - Optional - The y-coordinate for blending.
### Returns
BitmapBuilder - A new BitmapBuilder instance with the subtracted bitmap.
```
```APIDOC
## multiply()
### Description
Multiplicative blend.
### Method
(Implicitly called on BitmapBuilder instance)
### Parameters
- **other** (BitmapBuilder | Bitmap) - Required - The bitmap to multiply.
- **x** (number) - Optional - The x-coordinate for blending.
- **y** (number) - Optional - The y-coordinate for blending.
### Returns
BitmapBuilder - A new BitmapBuilder instance with the multiplied bitmap.
```
```APIDOC
## max()
### Description
Maximum blend.
### Method
(Implicitly called on BitmapBuilder instance)
### Parameters
- **other** (BitmapBuilder | Bitmap) - Required - The bitmap to blend.
- **x** (number) - Optional - The x-coordinate for blending.
- **y** (number) - Optional - The y-coordinate for blending.
### Returns
BitmapBuilder - A new BitmapBuilder instance with the maximum blended bitmap.
```
```APIDOC
## convert()
### Description
Convert to a different pixel mode.
### Method
(Implicitly called on BitmapBuilder instance)
### Parameters
- **targetMode** (PixelMode) - Required - The target pixel mode.
### Returns
BitmapBuilder - A new BitmapBuilder instance with the converted pixel mode.
```
```APIDOC
## toRGBA()
### Description
Get the bitmap as an RGBA pixel array.
### Method
(Implicitly called on BitmapBuilder instance)
### Returns
Uint8Array - The RGBA pixel data.
```
```APIDOC
## toGray()
### Description
Get the bitmap as a grayscale pixel array.
### Method
(Implicitly called on BitmapBuilder instance)
### Returns
Uint8Array - The grayscale pixel data.
```
```APIDOC
## toBitmap()
### Description
Get a clone of the raw bitmap.
### Method
(Implicitly called on BitmapBuilder instance)
### Returns
Bitmap - A cloned Bitmap object.
```
```APIDOC
## toRasterizedGlyph()
### Description
Get the bitmap with bearing information.
### Method
(Implicitly called on BitmapBuilder instance)
### Returns
{ bitmap: Bitmap; bearingX: number; bearingY: number } - An object containing the bitmap and its bearing information.
```
```APIDOC
## clone()
### Description
Clone this builder.
### Method
(Implicitly called on BitmapBuilder instance)
### Returns
BitmapBuilder - A new BitmapBuilder instance that is a clone of the current one.
```
--------------------------------
### loadFontProgram
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/raster.md
Loads and executes the font program (fpgm) for a given hinting engine.
```APIDOC
## loadFontProgram
### Description
Load and execute font program (fpgm).
### Method Signature
```typescript
function loadFontProgram(engine: HintingEngine, fpgm: Uint8Array): void
```
```
--------------------------------
### Get Grayscale Pixel Array
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Retrieves the bitmap's pixel data as a grayscale Uint8Array. Each byte represents the intensity of a pixel.
```typescript
toGray(): Uint8Array
```
--------------------------------
### Get Flattened Glyph Contours
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/font.md
Retrieves the outline contours of a glyph, resolving composite glyphs. Works for both TrueType and CFF fonts.
```typescript
const contours = font.getGlyphContours(glyphId);
if (contours) {
for (const contour of contours) {
for (const point of contour) {
console.log(point.x, point.y, point.onCurve);
}
}
}
```
--------------------------------
### Get Glyph ID from Unicode or Character
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/tables.md
Map a Unicode codepoint or a character to its corresponding glyph ID using the Cmap table.
```typescript
const glyphId = font.glyphId(0x0041); // Unicode codepoint
const glyphId = font.glyphIdForChar("A"); // Character
```
--------------------------------
### Basic Text Shaping with Features
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/advanced/shape-plan.md
Demonstrates how to perform text shaping using the `shape` function, specifying script, language, direction, and enabled/disabled features.
```typescript
import { shape } from "text-shaper";
const result = shape(font, buffer, {
script: "arab",
language: "ARA",
direction: "rtl",
features: [
{ tag: tag("liga"), enabled: true },
{ tag: tag("kern"), enabled: false }
]
});
```
--------------------------------
### char()
Source: https://github.com/wiedymi/text-shaper/blob/main/docs/api/fluent.md
Creates a PathBuilder from a character. This is an entry point for the fluent API.
```APIDOC
## char()
### Description
Create a `PathBuilder` from a character.
### Signature
```typescript
function char(font: Font, character: string): PathBuilder | null
```
### Example
```typescript
const builder = char(font, "A");
const rgba = builder?.scale(2).rasterizeAuto().toRGBA();
```
```