本文介绍了在HTML5 canvas中创建关键事件的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请建议为HTML5 canvas创建关键事件的最佳方法。我不喜欢任何图书馆,但如果你认为这是最好的方法,然后去回答它。提前感谢!
Please suggest the best way to create key events for HTML5 canvas. I don't prefer any library, but if you think that it's the best way then go answer it. Thanks in advance!
推荐答案
这将返回键码:
<canvas id="myCanvas" width="200" height="100" style="background:green"></canvas>
<script type="text/javascript">
window.addEventListener('keydown',this.check,false);
function check(e) {
alert(e.keyCode);
}
</script>
如果您想根据键演示不同的操作:
If you would like a demonstration of different things being done based on key:
function check(e) {
var code = e.keyCode;
//Up arrow pressed
if (code == 38)
alert("You pressed the Up arrow key");
else
alert("You pressed some other key I don't really care about.");
}
或者如果你有一个很长的键列表,
Or if you have a long list of keys you'll be using, do it in a switch case:
function check(e) {
var code = e.keyCode;
switch (code) {
case 37: alert("Left"); break; //Left key
case 38: alert("Up"); break; //Up key
case 39: alert("Right"); break; //Right key
case 40: alert("Down"); break; //Down key
default: alert(code); //Everything else
}
}
这篇关于在HTML5 canvas中创建关键事件的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!