views:

171

answers:

3

I'm writing an application in which I need to simulate a textarea. The only way I know how to approach it is to capture the keyCode on a key event. How would one go about taking that keyCode and, supporting utf-8, apply that to the canvas?

Cheers

A: 

Have you seen Bespin? It is more than just a textarea replacement, but it basically does what you want. You could certainly look into the code and documentation, or if it fits your needs, just use it.

Russell Leggett
How do you know what they want? Are you a mind reader?
strager
I'll rephrase - it accomplishes the specific requirement they inquired about: "Javascript HTML5 Capture keyCode and write to Canvas" As a purely canvas based text editor, they capture keys typed in and display it using canvas - amongst other things.
Russell Leggett
+2  A: 

This seems like a bad idea since there is an awful lot over and above text input that a textarea gives you for free (caret, selection, cut, paste, drag and drop, arrow key handling, etc.), but here's two things you need to do :

  1. Give your <canvas> a tabindex attribute so that it may receive focus and hence raise key events;
  2. Add a keypress (not keydown) handler to the <canvas> element to capture text input.

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>
Tim Down
I think you may be right, it seems like an awful lot of work to replicate a textarea and I actually don't see any advantages of keeping a textarea out (it's not really an application, but more of an edutainment game where everything is happening in a canvas element but need to recieve text input). I *think* putting a transparent textarea over my canvas is the best possible solution.
roosta
A: 

Using jquery:

<div id="myTextArea></div>

$('#myTextArea').keypress(function (event) {

    $('#myTextArea').append(String.fromCharCode(event.which));

});
JungleFreak