photopea / Typr.js

Typr.js - process fonts in Javascript
MIT License
914 stars 73 forks source link

Feature: layout text? #6

Closed adriaanmeuris closed 7 years ago

adriaanmeuris commented 7 years ago

Any chance your library will support layout like multiline text and aligment like https://github.com/Jam3/opentype-layout?

photopea commented 7 years ago

Hi, it is extremely easy to create a function, that can generate such layout, once you understand the structure of Typr and a font. The idea is to measure the width of each word and then fill each line, until the width isn't reached. After filling, you can align words to the right - left - justify. You can even implement word-breaking etc.

adriaanmeuris commented 7 years ago

Great, any idea where to get started? I was thinking maybe the PDFkit source would be a good place to start (e.g. https://github.com/devongovett/pdfkit/blob/master/lib/line_wrapper.coffee). Any pointers would be appreciated.

photopea commented 7 years ago

First, read all the content at the beginning page of this project. Make sure, that you fully understand the code at the bottom.

When you have some text, split it into words ("Hello world, what is your name?").split(" ") Then measure each word by measuring the distance betwee pairs of characters - Typr.U.getPairAdjustment(...), the sum will be the width of the word. Once you have widths of words, e.g. [130, 50, 67, 82, 114, 38], you can split them into groups (lines), such that the sum of widths in each line is not bigger than your limit, e.g. [[130, 50], [67, 82, 114], [38]]. Then you can render them (two words on the first line, three words on the second, the last world on the third line).

Note, that this project https://github.com/Jam3/opentype-layout does not support using different fonts in a single block of the text, different font sizes, word-breaking, different alignments in a single block ... so I think it is always better to make such code specifically for your use case.

adriaanmeuris commented 7 years ago

perfect, thanks for your help!