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
Javascript HTML5 Capture keyCode and write to Canvas
提问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 免费为您提供了大量的文本输入(插入符号、选择、剪切、粘贴、拖放、箭头键处理等),但这里有两件事你需要做 :
- Give your
<canvas>atabindexattribute so that it may receive focus and hence raise key events; - Add a
keypress(notkeydown) handler to the<canvas>element to capture text input.
- 给你
<canvas>一个tabindex属性,这样它就可以得到焦点,从而引发关键事件; - 向元素添加一个
keypress(notkeydown) 处理程序<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));
});

