Javascript HTML5 捕获 keyCode 并写入 Canvas

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3729034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:03:38  来源:igfitidea点击:

Javascript HTML5 Capture keyCode and write to Canvas

javascripthtmlcanvaskeycode

提问by Russell

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?

我正在编写一个应用程序,我需要在其中模拟文本区域。我知道如何处理它的唯一方法是在关键事件上捕获 keyCode。如何获取该 keyCode 并支持 utf-8,并将其应用于画布?

Cheers

干杯

回答by Tim Down

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 :

这似乎是一个坏主意,因为 textarea 免费为您提供了大量的文本输入(插入符号、选择、剪切、粘贴、拖放、箭头键处理等),但这里有两件事你需要做 :

  1. Give your <canvas>a tabindexattribute 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.
  1. 给你<canvas>一个tabindex属性,这样它就可以得到焦点,从而引发关键事件;
  2. 向元素添加一个keypress(not keydown) 处理程序<canvas>以捕获文本输入。

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>

回答by Rohrbs

Using jquery:

使用jQuery:

<div id="myTextArea></div>

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

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

});

回答by Russell Leggett

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.

你见过贝斯平吗?它不仅仅是一个 textarea 替换,但它基本上可以满足您的需求。您当然可以查看代码和文档,或者如果它符合您的需求,就使用它。