JavaScript canvas: write within box -
in js canvas, how can place text within "box", ora have stay in rectangle? mean, can place text @ x, y coordinate, i'd lay in surround box x0, y0, x1, y1, have line breaks when text go out of box, can center within rectangle , possibly have text scaled fit as box possible.
is there such library so?
hope you
<!doctype html> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas id="mycanvas" width="578" height="200"></canvas> <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 && n > 0) { context.filltext(line, x, y); line = words[n] + ' '; y += lineheight; } else { line = testline; } } context.filltext(line, x, y); } 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 = 'all world \'s stage, , men , women merely players. have exits , entrances; , 1 man in time plays many parts.'; context.font = '16pt calibri'; context.fillstyle = '#333'; wraptext(context, text, x, y, maxwidth, lineheight); </script> </body> </html>
Comments
Post a Comment