Created
May 4, 2020 12:30
-
-
Save oakfang/9b160460be5f202bb2f80c4312112803 to your computer and use it in GitHub Desktop.
Calculating the approximate height of text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import stringPixelWidth from "string-pixel-width"; | |
export function getTextHeight(text, { textBlockWidth, lineHeight = 1.15, fontSize }) { | |
const paragraphs = text.split('\n'); | |
const lineCountPerParagraph = paragraphs.map(paragraph => { | |
const words = paragraph.split(' '); | |
const [lineCount] = words.reduce(([lines, line], word, idx) => { | |
const expandedLine = line ? line + ` ${word}` : word; | |
if (stringPixelWidth(expandedLine, {size: fontSize}) < textBlockWidth) { | |
return [lines, expandedLine] | |
} | |
return [lines + 1, word] | |
}, [1, '']); | |
return lineCount; | |
}); | |
const totalLineCount = lineCountPerParagraph.reduce((countA, countB) => countA + countB); | |
return totalLineCount * fontSize * lineHeight | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment