Wrap-text

measuring text

HTML

<canvas id="myCanvas" width="200" height="150"></canvas>

CSS

#myCanvas {
    border: 1px solid black;
}

JavaScript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var text = "Here's a long text that I'd like to wrap into a certain width. I really hope that my function will be able to handle this, YIKES!";

wrapText(200,text,0,20,20,"Arial");

function wrapText(wrapWidth,textString,startX,startY,fontSize,fontFamily) {
    var words = textString.split(" "); // split the string into words
    var tempText="";
    var currentY=startY; // this is to keep track on where on the canvas we are
    ctx.font= fontSize+"pt "+fontFamily
    var lnCnt =0;
    for (var i=0; i<words.length; i++) { // looping through all words
		// checking if adding one more word exceeds the allowed width
        if (ctx.measureText(tempText+" "+words[i]).width>wrapWidth) {
            ctx.fillText(tempText,startX,currentY); // print the finished row
            currentY+=fontSize+4; // go to next row, 4 is line spacing
            tempText=""; // empty the temporary text string
            i--; // since the last word wasn't added, we need to start with that one.
            lnCnt++;
        }
        else {
            tempText+=" "+words[i];
        }
    }
    alert(lnCnt+1);
    ctx.fillText(tempText,startX,currentY); // above, we only print full lines, last row is filled.
}