Introduction
This article shows how to wrap text using the HTML 5 canvas tag; we can create a custom function that requires the canvas context, a text string, a position, a max-width, and a line-height. The function should use the measureText() method of the canvas context to calculate when the next line should wrap.
Here we will use some JavaScript and some styles along with HTML code. Just go through the steps to see how to create this application.
Let's see how the CanvasWrapTextApp application can be created. To do so use the following steps.
Step 1 : Open a HTML editor or Visual Studio.
Open File menu ->select new ->Choose Website

- Go to Solution Explorer
- Right-click on the Application name
- Select Add-->add new item
- Now in the window that opens, select an HTML page or new Webform
- Rename it to Canvaswraptext.aspx

CSS Script
- <style>
- body
- {
- margin: 0px;
- padding: 0px;
- }
- Canvas
- {
- border: 2px solid #9C9898;
- margin-top: 50px;
- margin-left: 50px;
- background-color: #F4D19F;
- box-shadow: 5px 5px 8px #222;
- }
- .title
- {
- text-align: center;
- font-family: Segoe UI Light, Arial, Helvetica;
- font-size: 2.2em;
- margin: 1em;
- }
- .info
- {
- text-align: center;
- font-family: Segoe UI Light, Arial, Helvetica;
- font-size: 1.2em;
- margin: 0.25em;
- }
- </style>
The whole JavaScript looks as in the following:
- <script>
- 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);
- }
- window.onload = function () {
- var canvas = document.getElementById("myCanvas");
- var context = canvas.getContext("2d");
- var maxWidth = 400;
- var lineHeight = 25;
- var x = (canvas.width - maxWidth) / 2;
- var y = 60;
- var text = "Mahesh is the founder of C# Corner and Mindcracker Network, 7-times Microsoft MVP and author of several .NET programming books. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries";
- context.font = "16pt Calibri";
- context.fillStyle = "#333";
- wrapText(context, text, x, y, maxWidth, lineHeight);
- };
- </script>


Gowtham RajamanickamPosted Apr 11, 2015, 1:31 PM
well explained
Gowtham RajamanickamPosted Apr 11, 2015, 1:31 PM
good one
VerenaJamPosted Sep 19, 2014, 12:36 AM
Hi Deepak Thanks for the wonderful code, can you please tell me how to code in WindowForm of Visual studio using c#, if you dont mind. With many thanks