layout-bmfont-text

unstable

screenshot

(click for demo)

Provides layout and word-wrapping for left-to-right text, primarily aimed at bitmap font rendering in Canvas/WebGL. The input font should be in the format of BMFont json, see here.

You can use bmfont-lato for testing.

var createLayout = require('layout-bmfont-text')
var font = require('bmfont-lato')

var layout = createLayout({
  font: font,
  text: 'Lorem ipsum dolor\nsit amet',
  width: 300,
  letterSpacing: 2,
  align: 'center'
})

//for rendering
console.log(layout.glyphs)

//metrics
console.log(layout.width, layout.height)
console.log(layout.descender, layout.ascender)

Features:

Comments/suggestions/PRs welcome.

Usage

NPM

layout = createLayout(opt)

Creates a new layout with the given options.

layout.update(opt)

Updates the layout, all options are the same as in constructor.

layout.glyphs

An array of laid out glyphs that can be used for rendering. Each glyph looks like this:

{
    index: i,        //the index of this glyph into the string
    data: {...},     //the BMFont "char" object for this glyph
    position: [x, y] //the baseline position to render this glyph
}

All positions are relative to the bottom-left baseline of the text box (i.e. the last line).

layout.width

The width of the text box, or the width provided in constructor.

layout.height

The height of the text box; from baseline to the top of the ascender.

metrics

layout.baseline

The baseline metric: measures top of text layout to the baseline of the first line.

layout.xHeight

The x-height metric; the height of a lowercase character. Uses the first available height of the following: ‘x’, ‘u’, ‘v’, ‘w’, ‘z’.

layout.descender

The metric from baseline to the bottom of the descenders (like the bottom of a lowercase “g”).

layout.ascender

The metric for ascenders; typically from the top of x-height to the top of the glyph height.

License

MIT, see LICENSE.md for details.