Javascript examples for Canvas:Text
Break text when drawing on canvas
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://code.jquery.com/jquery-1.4.4.min.js"></script> <style id="compiled-css" type="text/css"> canvas{background-color:#ccc;} </style> <script type="text/javascript"> $(window).load(function(){// w ww . j av a2 s . c om var c = $('#c')[0].getContext('2d'); c.font = '11px Courier'; var txt = 'this is a very long text to print'; printAt(c, txt, 10, 20, 15, 90 ); function printAt( context , text, x, y, lineHeight, fitWidth) { fitWidth = fitWidth || 0; if (fitWidth <= 0) { context.fillText( text, x, y ); return; } for (var idx = 1; idx <= text.length; idx++) { var str = text.substr(0, idx); console.log(str, context.measureText(str).width, fitWidth); if (context.measureText(str).width > fitWidth) { context.fillText( text.substr(0, idx-1), x, y ); printAt(context, text.substr(idx-1), x, y + lineHeight, lineHeight, fitWidth); return; } } context.fillText( text, x, y ); } }); </script> </head> <body> <canvas id="c" width="150" height="150"></canvas> </body> </html>