jsText library

November 13th 2013 by Samuel Rossille

jsText is a small library made to modelize and handle text rendering at letter level in javascript. Why this ?


Here is an example of what you can do. Resize the box to see text layout update. Note the three dots at the end of the text, and the performance of the layout update.

Code sample

What you would typically write:

// this how we create a Flow

var flow = $.jsText.flow("The text on which we want to work.", {
    "font-family": "Verdana, Helvetica, Arial, sans-serif",
    "font-size": "1em"

// "flow" contains the words and letters metrics information and we
// can perform as many layout as we want with the same flow. 

// now let's do a layout in a rectangular 50 x 50 square.

var layout = flow.layout({width: 50, height: 50});  

// "layout" contains the information about how to split the text into lines
// to make it fit in a 50 x 50 square.

// Note that at this point we are still independent of the rendering-material 
// (SVG, HTML, PDF, Canvas, VML ?)

// Now we want to show something ... in html for example.

layout.render("top", "left", function(line, x, y) { // this anonymous function will be 
    target.append($("<div/>").css({                 // called for each chunk of text
        position: "absolute",
        x: x + "px",
        y: y + "px",

More about the concepts

A flow is an object that contains all the metric information related to a text. It contains the measures of each letter and word. Creating it from a string is the expensive operation. It makes no assumption about how the text will be displayed.

The text's basic elements measures are the information are used to create a layout from a flow. The layout() method of a flow implements this operation.

The layout specifies how the text is split into several lines, and where these lines should be on a media. The layout doesn't require any assumptions on the final rendring media. Basically it's just a collection of chunks of text with placement information on a bidimensionnal space.

To actually display the original text with this layout on a media, we need to perform a media-dependent rendering. The render() method of a layout allows to perfrom the actual rendering through a user supplied function that will be called for each chunk of text, with the string to display and the placement information for each of them.

Get it!

Github: master