Javascript HTML5 Capturing keyCode and writing to canvas

I am writing an application in which I need to simulate a text box. The only way I know how to do this is to capture keyCode on a key event. How could one take this keyCode and, supporting utf-8, apply this to the canvas?

Greetings

+7
javascript html5 canvas keycode
source share
3 answers

This seems like a bad idea, as there is a lot of extra text and text input that provides a text box for free (carriage, select, cut, paste, drag and drop, manipulate arrow keys, etc.), but here are two things you need to do:

  • Give the attribute <canvas> a tabindex so that it can receive focus and therefore increase key events;
  • Add a keypress (not keydown ) element to the <canvas> to enter text.

the code:

 <canvas id="textarea" tabindex="1" width="300" height="200"></canvas> <script type="text/javascript"> var el = document.getElementById("textarea"); el.onkeypress = function(evt) { var charCode = evt.which; var charStr = String.fromCharCode(charCode); alert(charStr); }; </script> 
+10
source share

Using jquery:

 <div id="myTextArea></div> $('#myTextArea').keypress(function (event) { $('#myTextArea').append(String.fromCharCode(event.which)); }); 
+3
source share

Have you seen Bespin ? This is more than just a replacement for textarea, but basically does what you want. You could probably study the code and documentation, or if it suits your needs, just use it.

+1
source share

All Articles