Friday, February 19th, 2010
TeX line breaking algorithm in JavaScript
Bram Stein has done some really fun work. He has taken the Knuth and Plass line breaking algorithm and implemented it using Canvas:
The goal of this implementation is to optimally set justified text in the new HTML5 canvas element, and ultimately provide a library for various line breaking algorithms in JavaScript.
You can see the subtleties at work:
Check out the linebreak code which does more than solely justification. It can also perform all sorts of alignment with an appropriate selection of boxes, glue and penalties. It is also possible to give it varying line widths to flow text around illustrations, asides or quotes. Alternatively, varying line widths can be used to create interesting text shapes.





It does not feels right to use canvas for text.
You could probably remove all spaces and replace them with span elements (inline-block) with correct widths. No need to use canvas here.
Can someone please just implement a canvas tag in canvas and be done with it?
As a typesetter and a web designer, this brings joy to my heart :)
Looks lovely. Now if only the text were selectable… add that to your TODOs!
been doing this with javascript without canvas for years.
To tell the truth, I find the browser’s rendition more readable.
Knuth is severly overrated, as we all know.