Wednesday, 18 July 2012

HTML5 - Wrap Text in Canvas

It is very important feature that should be included with draft of new features of html5 canvas but unfortunately its not included. I have developed function that makes it possible to wrap text inside the canvas.

Here is the code that will wrap the text on end of the canvas width. It is written in javascript. So to use just add it to your javascript.

Parameter Details:

  • context = canvas context variable name.
  • text = Whole text string that to be added in the canvas.
  • x = starting x point of the text in the canvas.
  • y = starting y point of the text in the canvas.
  • maxWidth = canvas's width.
  • lineHeight = Distance between two lines.
function wrapText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split(" ");
        var line = "";
        for(var n = 0; n < words.length; n++) {
          var testLine = line + words[n] + " ";
          var metrics = context.measureText(testLine);
          var testWidth = metrics.width;
          if(testWidth > maxWidth) {
            context.fillText(line, x, y);
            line = words[n] + " ";
            y += lineHeight;
          }
          else {
            line = testLine;
          }
        }
        context.fillText(line, x, y);
}

For Ex. 
   var text = "HTML5 Wrap Text function in Javascript written here is helped me a lot.";
   var x = 20;
   var y = 20;
   wrapText(context, text, x, y, (canvas.width - 8), 25)

* line Height 25 because mine font size is 20.

Note : Single canvas for single paragraph is to be used.

Hope this will help you a lot to all HTML5 Developer. Give your comments to improve this article.

2 comments:

Comment anytime to improve this article.
You can comment as anonymous to comment without account.