Advertisement
Guest User

Untitled

a guest
Feb 5th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. function getCharWidthInPixels(c) {
  2. return 1; // TODO: mocked, replace with real pixel counting implementation
  3. }
  4.  
  5. function displayText(text, pixelWidth) {
  6.  
  7. var lineStartIndex = 0;
  8. var currentIndex = 0;
  9. var lastWordIndex = 0;
  10. var totalLineWidth = 0;
  11.  
  12. var result = new Array();
  13.  
  14. var textLength = text.length;
  15.  
  16. while(lineStartIndex < textLength) {
  17.  
  18. var currentChar = text[currentIndex];
  19. var currentCharIsWhiteSpace = currentChar == ' ';
  20. var currentCharWidth = getCharWidthInPixels(currentChar);
  21.  
  22. if (currentCharIsWhiteSpace) {
  23. if (lineStartIndex == currentIndex) { // Trim left spaces
  24. ++currentIndex;
  25. lineStartIndex = currentIndex;
  26. lastWordIndex = lineStartIndex;
  27. continue;
  28. }
  29. lastWordIndex = currentIndex;
  30. } else {
  31. if (currentIndex >= textLength - 1) { // If the end of the string is reached mark has a word
  32. lastWordIndex = currentIndex + 1;
  33. }
  34. }
  35.  
  36. totalLineWidth = totalLineWidth + currentCharWidth;
  37.  
  38. if (
  39. totalLineWidth > pixelWidth &&
  40. lastWordIndex > lineStartIndex
  41. ) {
  42. var line = text.substr(lineStartIndex, lastWordIndex - lineStartIndex);
  43. result.push(line);
  44. lineStartIndex = lastWordIndex + 1;
  45. lastWordIndex = lineStartIndex;
  46. totalLineWidth = 0;
  47. }
  48.  
  49. ++currentIndex;
  50. }
  51.  
  52. return result;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement