Basically what I’ve done is making a simple animation that moves a rectangle the x-axis while the enter key is being held down. This works fine, but the problem is that when you press the enter key the rectangle seems to jump foward about 10px or so. Not sure what is causing this.
//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);
Any help is appreciated!
This is because your requestAnimationFrame is always running (Which is good). Your tick is being incremented every single time it’s called. If you wait a long time before hitting enter, you’ll notice it starts a lot further to the right.
My suggestion is to move the
tick++into theif(key == true)portion.