Javascript examples for Canvas:Key
HTML canvas dynamically enter text boxes values into canvas on keypress
<!doctype html> <html> <head> <!-- reset css --> <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> <style> canvas{border:1px solid red;} </style> <script> $(function(){//w w w. jav a2 s . com var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var $text1=document.getElementById("sourceText1"); var $text2=document.getElementById("sourceText2"); $text1.onkeyup=function(e){ redrawTexts(); } $text2.onkeyup=function(e){ redrawTexts(); } function redrawTexts(){ ctx.clearRect(0,0,canvas.width,canvas.height); wrapText(ctx,$text1.value,20,60,100,24,"verdana"); wrapText(ctx,$text2.value,150,60,100,24,"verdana"); } function wrapText(context, text, x, y, maxWidth, fontSize, fontFace){ var words = text.split(' '); var line = ''; var lineHeight=fontSize; context.font=fontSize+" "+fontFace; 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); return(y); } }); </script> </head> <body> <h4>Type text to wrap into canvas.</h4> <input id="sourceText1" type="text"> <input id="sourceText2" type="text"> <br> <canvas id="canvas" width="300" height="300"></canvas> </body> </html>