Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function wrapText(text, maxWidth = 100, lineHeight = 10, offsetX = 0) {
- var cars = text.split("\n");
- for (var ii = 0; ii < cars.length; ii++) {
- //console.log(cars.length, ii);
- var line = "";
- var words = cars[ii].split(" ");
- for (var n = 0; n < words.length; n++) {
- var testWord = words[n];
- var testLine = line + testWord;// + " ";
- var testLineWidth = measureText(testLine).width;
- testLine += " ";
- if (testLineWidth > maxWidth) {
- var lengthToEnd = maxWidth-measureText(line).width;
- console.log("testLineWidth "+testLine+" = "+testLineWidth+">"+maxWidth+" is too big!");
- var wordWidth = measureText(testWord).width;
- var secondPart = "";
- if (wordWidth > maxWidth){
- console.log("even word "+testWord+" is too big! "+wordWidth);
- var b = 0;
- while(wordWidth > maxWidth && b < 100){
- b++;
- var symbolWidth = wordWidth/testWord.length;
- lengthToEnd = maxWidth-measureText(line).width;
- var maxN = Math.floor( (lengthToEnd)/symbolWidth );
- if (maxN > 0){
- var firstPart = testWord.substring(0,maxN);
- console.log("but "+firstPart+" is ok");
- secondPart = testWord.substring(maxN,testWord.length);
- addLine(line+firstPart, lineHeight, offsetX + ((maxWidth-measureText(line+firstPart).width)/2).clamp(0,maxWidth));
- line = "";
- wordWidth = measureText(secondPart).width;
- testWord = secondPart;
- }
- else{
- console.log("and we can't add anything here", line, context.measureText(line).width, symbolWidth );
- wordWidth = measureText(testWord).width;
- addLine(line, lineHeight, (offsetX + lengthToEnd/2).clamp(0,maxWidth));
- line = "";
- }
- }
- line = testWord;// + " ";
- console.log(testWord+" is only "+wordWidth+" so now '"+line+"' is ok. Go next?");
- }
- else{
- console.log(testWord+" wordWidth "+wordWidth+"<"+maxWidth+", so go next line writing "+line);
- addLine(line, lineHeight, offsetX + (lengthToEnd/2).clamp(0,maxWidth));
- line = testWord;// + " ";
- }
- }
- else {
- line = testLine;
- }
- }
- addLine(line, lineHeight, offsetX + ((maxWidth-measureText(line).width)/2).clamp(0,maxWidth));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement