Text measure and flow layout utility
JavaScript
Latest commit e7427fd Aug 27, 2013 @rossille wip on jquery plugin

README.md

Overview

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

  • Multiline text-overflow: ellipsis
  • Multiline text with technologies that does not support it: SVG, Canvas for example
  • Have exactly the same line breaks in your SVG text, in your HTML rendering, and in your PDF export for example
  • More generally, precicely control and monitor the rendering of the text in your application or page.

Demo!

Check out this: http://www.samuelrossille.com/home/jstext.html

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 that can be 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.