Skip to content

Instantly share code, notes, and snippets.

@oakfang
Created May 4, 2020 12:30
Show Gist options
  • Save oakfang/9b160460be5f202bb2f80c4312112803 to your computer and use it in GitHub Desktop.
Save oakfang/9b160460be5f202bb2f80c4312112803 to your computer and use it in GitHub Desktop.
Calculating the approximate height of text
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