requestanimationframe、keydown、keyup的使用
首选创建画布
<canvas id="canvas" width="700" height="600"></canvas>
获取画布
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
//动画
function animation(){
if (direction == -1) {
//向左移动动画
} else if (direction == 1) {
//向右移动动画
}
//这里写要执行的动画
requestAnimationFrame(animation);
}
animation();
//键盘绑定事件
var direction = 0
document.addEventListener('keydown', function (evt) {
switch (evt.which) {
case 37: // left
direction = -1;
break;
case 39: // right
direction = 1;
break;
}
document.addEventListener('keyup', function (evt) {
if ((evt.which == 37 && direction < 0) ||
(evt.which == 39 && direction > 0)) {
direction = 0;
}
});
});