Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getCharWidthInPixels(c) {
- return 1; // TODO: mocked, replace with real pixel counting implementation
- }
- function displayText(text, pixelWidth) {
- var lineStartIndex = 0;
- var currentIndex = 0;
- var lastWordIndex = 0;
- var totalLineWidth = 0;
- var result = new Array();
- var textLength = text.length;
- while(lineStartIndex < textLength) {
- var currentChar = text[currentIndex];
- var currentCharIsWhiteSpace = currentChar == ' ';
- var currentCharWidth = getCharWidthInPixels(currentChar);
- if (currentCharIsWhiteSpace) {
- if (lineStartIndex == currentIndex) { // Trim left spaces
- ++currentIndex;
- lineStartIndex = currentIndex;
- lastWordIndex = lineStartIndex;
- continue;
- }
- lastWordIndex = currentIndex;
- } else {
- if (currentIndex >= textLength - 1) { // If the end of the string is reached mark has a word
- lastWordIndex = currentIndex + 1;
- }
- }
- totalLineWidth = totalLineWidth + currentCharWidth;
- if (
- totalLineWidth > pixelWidth &&
- lastWordIndex > lineStartIndex
- ) {
- var line = text.substr(lineStartIndex, lastWordIndex - lineStartIndex);
- result.push(line);
- lineStartIndex = lastWordIndex + 1;
- lastWordIndex = lineStartIndex;
- totalLineWidth = 0;
- }
- ++currentIndex;
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement