基本上我所做的是制作一个简单的动画,在按住回车键的同时将一个矩形移动到 x 轴。这很好用,但问题是当你按下回车键时,矩形似乎向前跳跃了大约 10px 左右。不确定是什么原因造成的。
//event listener
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);
function onKeyDown(event){
var keyCode = event.keyCode;
switch(keyCode){
case 13: //enter
key = true;
break;
}
}
function onKeyUp(event){
var keyCode = event.keyCode;
switch(keyCode){
case 13: //enter
key = false;
break;
}
}
//neccessary variables
var tick = 0;
var key = false;
//main animation function
function drawStuff(){
window.requestAnimationFrame(drawStuff);
var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");
if(key == true){
c.clearRect(0,0,500,500);
c.fillStyle = "blue";
c.fillRect(tick,0,100,100);
}
else{
}
tick++;
}
window.requestAnimationFrame(drawStuff);
任何帮助表示赞赏!