measure-text.js 859 B

123456789101112131415161718192021222324252627282930313233343536
  1. export function measureText(font, text) {
  2. let x = 0;
  3. for (let i = 0; i < text.length; i++) {
  4. if (font.chars[text[i]]) {
  5. const kerning =
  6. font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]]
  7. ? font.kernings[text[i]][text[i + 1]]
  8. : 0;
  9. x += (font.chars[text[i]].xadvance || 0) + kerning;
  10. }
  11. }
  12. return x;
  13. }
  14. export function measureTextHeight(font, text, maxWidth) {
  15. const words = text.split(' ');
  16. let line = '';
  17. let textTotalHeight = font.common.lineHeight;
  18. for (let n = 0; n < words.length; n++) {
  19. const testLine = line + words[n] + ' ';
  20. const testWidth = measureText(font, testLine);
  21. if (testWidth > maxWidth && n > 0) {
  22. textTotalHeight += font.common.lineHeight;
  23. line = words[n] + ' ';
  24. } else {
  25. line = testLine;
  26. }
  27. }
  28. return textTotalHeight;
  29. }