Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript HTML5 Capture keyCode and write to Canvas

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

like image 932
Russell Avatar asked Sep 16 '10 17:09

Russell


People also ask

How do I put text on a canvas in HTML?

To add a text to the HTML <canvas> element, you need to use the fillText() or strokeText() methods, or you can use the combination of the two. You can also give color to your text, define the font and size, and even add gradients.

Does HTML5 support canvas element?

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.

Does JavaScript work in canvas?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.

Is HTML5 Canvas fast?

On the one hand, canvas was fast enough on simple functions like pencil drawing due to native implementation of basic drawing methods. On the other hand, when we implemented classic Flood Fill algorithm using Pixel Manipulation API we found that it is too slow for that class of algorithms.


2 Answers

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>
like image 177
Tim Down Avatar answered Nov 08 '22 06:11

Tim Down


Using jquery:

<div id="myTextArea></div>

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

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

});
like image 35
Rohrbs Avatar answered Nov 08 '22 07:11

Rohrbs