javascript - HTML5 edit text on the canvas -
i'm trying create similar http://www.listhings.com can edit text within canvas.
i've read other post html5 canvas text edit . don't want edit text outside of canvas. want edit text within canvas.
i'd appreciate if can point me in right direction.
thanks
first, mohsen correctly points out when context.filltext "painting picture of letters" on canvas. it's not word processor!
you can capture key events on window , write keystrokes out canvas.
here code , fiddle: http://jsfiddle.net/m1erickson/7txd4/
this example types lowercase a-z (no capitals, spaces, backspaces, etc)
you want make more enhancements these:
- adding more keys (a-z, 0-9, etc).
- respond command keys backspace remove letters keyhistory.
- put cursor users know on line type (hint: http://www.html5canvastutorials.com/tutorials/html5-canvas-text-metrics/)
- if allow multi-line text, handle [enterkey] , move new line.
- etc
here's code just started:
<!doctype html> <html> <head> <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <style> body{ background-color: ivory; padding:20px; } canvas{border:1px solid red;} </style> <script> $(function(){ var canvas=document.getelementbyid("canvas"); var ctx=canvas.getcontext("2d"); ctx.font="18px arial"; var keyhistory=""; window.addeventlistener("keyup", keyuphandler, true); function addletter(letter){ keyhistory+=letter; ctx.clearrect(0,0,300,300); ctx.filltext(keyhistory,20,20); } function keyuphandler(event){ var letters="abcdefghijklmnopqrstuvwxyz"; var key=event.keycode; if(key>64 && key<91){ var letter=letters.substring(key-64,key-65); addletter(letter); } } }); // end $(function(){}); </script> </head> <body> <p>first click in red canvas below</p><br/> <p>then type lowercase letters a-z</p><br/> <canvas id="canvas" width=300 height=100></canvas> </body> </html>
Comments
Post a Comment