最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript HTML5 Capture keyCode and write to Canvas - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question asked Sep 16, 2010 at 17:14 RussellRussell 9786 gold badges13 silver badges30 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 10

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>

Using jquery:

<div id="myTextArea></div>

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

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

});

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.

发布评论

评论列表(0)

  1. 暂无评论