Skip to content

Commit

Permalink
Merge pull request #23 from vladgolubev/master
Browse files Browse the repository at this point in the history
Allow set max font size when `sizeToFill: true`
  • Loading branch information
namniak authored Oct 5, 2016
2 parents d394674 + 1315d05 commit 86b7536
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ CanvasTextWrapper(HTMLCanvasElement, String [, options]);
| **fitParent** | *Boolean* | Fit canvas' container size instead of its own size. |
| **lineBreak** | `"auto"` `"word"` | `"auto"` - text goes to the next line on a whole word when there's no room `"word"` - each next word is placed on a new line |
| **sizeToFill** | *Boolean* | Ignore given font size and line height and resize text to fill its padded container. |
| **maxFontSizeToFill** | *Number* | If above option is `true` text won't be bigger than set. |
| **strokeText** | *Boolean* | Allow text outline based on canvas context configuration. |
| **justifyLines** | *Boolean* | All lines will try to match the same width with flexed spaces between the words. |
| **allowNewLine** | *Boolean* | Text breaks on a new line character "\n". Note it doesn't support multiple new lines, so `"\n\n\n"` will be rendered the same as a single `"\n"`. |
Expand All @@ -41,6 +42,7 @@ NOTE: if a single word is too long to fit the width with specified font size, it
lineBreak: 'auto',
strokeText: false
sizeToFill: false,
maxFontSizeToFill: false,
allowNewLine: true,
justifyLines: false,
renderHDPI: true,
Expand Down
12 changes: 11 additions & 1 deletion canvas-text-wrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
var defaults = {
font: '18px Arial, sans-serif',
sizeToFill: false,
maxFontSizeToFill: false,
lineHeight: 1,
allowNewLine: true,
lineBreak: 'auto',
Expand Down Expand Up @@ -99,9 +100,18 @@
if (opts.sizeToFill) {
var wordsCount = text.trim().split(/\s+/).length;
var newFontSize = 0;
var fontSizeHasLimit = opts.maxFontSizeToFill !== false;

do {
adjustFontSize(++newFontSize);
if (fontSizeHasLimit) {
if (++newFontSize <= opts.maxFontSizeToFill) {
adjustFontSize(newFontSize);
} else {
break;
}
} else {
adjustFontSize(++newFontSize);
}
} while (textBlockHeight < MAX_TXT_HEIGHT && (lines.join(' ').split(/\s+/).length == wordsCount));

adjustFontSize(--newFontSize);
Expand Down

0 comments on commit 86b7536

Please sign in to comment.