Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - What's the best way to create key events in 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will return the key code:

<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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...