Code Monkey home page Code Monkey logo

word-wrapper's Introduction

word-wrapper

stable

img

click here for a Canvas demo

This is a generic word wrapper for left-to-right text in 2D applications. It can be used in console, canvas, WebGL, etc. Accepts a custom measure function for glyph metrics.

The simplest use-case:

var text = wrap('the quick brown fox jumps over the lazy dog', { width: 8 })
console.log(text)

This will print the following:

the
quick
brown
fox
jumps
over the
lazy dog

In 2D applications it's more common to layout the text manually. For this we can use wrap.lines() to operate on a list of { start, end } indices. Then each line can be rendered with text.substring(line.start, line.end). An example:

//for example...
var lines = wrap.lines(text, { width: 40 })

//operate on the lines...
var text = lines
        .map( x => text.substring(x.start, x.end) )
        .join('\n')

See demo/canvas for a full 2D example.

Usage

NPM

text = wordwrap(text[, opt])

Word-wraps the text string with the given options. Returns a string with the word-wrapped result.

  • start the starting index to word-wrap, default 0
  • end the ending index to word-wrap (exclusive), default text.length
  • width the width to word wrap to, in 'units' (see below)
  • measure a function that measures the number of glyphs that can fit in (see measure). Defaults to monospace (i.e. 1 char is 1 unit)
  • mode can be 'pre' (maintain spacing), or 'nowrap' (collapse whitespace but only break on newline characters), otherwise assumes normal word-wrap behaviour

The width is measured in 'units' which could be pixels, centimeters, characters, etc. By default, one "unit" corresponds to one character (i.e. for monospace console rendering). To wrap text to a pixel width, you should use a custom measure function.

If mode is "pre" and width is specified, it will clip the characters to the given width (to avoid them over-flowing outside the bounds).

lines = wordwrap.lines(text[, opt])

Takes the same parameters as the above method, but returns a list of "lines" objects for manual text layout/rendering. A "line" is typically an object with { start, end } indices that can be used with text.substring(start, end). The "line" is the return value from the measure function, so it may also include application-specific data (i.e. to avoid re-computing line widths).

measure

To layout glyphs in 2D space, you typically will need to measure the width of each glyph (and its x-advance, kerning, etc) to determine the maximum number of glyphs that can fit within a specified available width.

You can pass a custom measure function which takes the text being wrapped, the start (inclusive) and end (exclusive) indices into the string, and the desired width. The return value should be an object with { start, end } indices, representing the actual glyphs that can be rendered within those bounds.

For example, a Canvas2D implementation that uses monospace fonts might look like this:

//the canvas font style
var font = '24px "Courier New", monospace'

//compute width
var measure = createMetrics(context, font)

function createMetrics(context, font) {
    context.font = font
    var charWidth = context.measureText('M').width

    return function measure(text, start, end, width) {
        //measures the chunk of text, returning the substring
        //we can fit within the given width
        var availableGlyphs = Math.floor(width/charWidth)
        var totalGlyphs = Math.floor((end-start)*charWidth)
        var glyphs = Math.min(end-start, availableGlyphs, totalGlyphs)
        return {
            start: start,
            end: start+glyphs
        }
    }
}

function draw(context) {
    var lines = wordwrap(text, { measure: measure, width: 200 })

    //draw the lines.. 
}

License

The original implementation is based on LibGDX's word wrapper.

MIT, see LICENSE.md for details.

word-wrapper's People

Contributors

mattdesl avatar mougrim avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.