var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
var xPosition = 0;
var yPosition = 0;
var frameLength = 20;
function gameLoop(){
gameUpdate();
setTimeout(function(){gameLoop()}, frameLength);
}
function gameUpdate(){
ctx.clearRect(0, 0, 480, 640);
window.addEventListener('keydown', function(event){switch(event.keyCode){case 38: yPosition -= 1; break; case 40: yPosition += 1; break;}}, false);
ctx.fillRect(xPosition, yPosition, 50, 50);
}
$(document).ready(function () {
gameLoop();
});
I'm trying to move a rectangle in canvas via arrow keys. X and Y positions are variables xPosition and yPosition. Dealing strictly with the Y-direction for now, I have a switch function triggered by an eventlistener for "keydown." When, for example, the DOWN-Arrow key is pressed, it increments the Y value in fillRect(X, Y, originX, OriginY)
. This changes the global variable, then the new rectangle with new coordinates is drawn on the Canvas. GameLoop resets, rinse repeat. That's how I perceive it to work in theory.
For some reason, however, even if I do nothing at all, the longer I let the script run, the "farther" the square jumps when I press UP or DOWN. That is, pressing down launches it off the canvas ever so many pixels that is determined by the number of loops setTimeout has gone through, it appears. Why is this, and how do I address it?