Keypresse and releases

In my code I want my image to move right when the right arrow key is pressed (which it already does) then to stop when you release it, also is their an easier way to write/remember the keyboard numbers?

const FPS = 30;
var x = 0;
var y = 0;
var image = new Image();
image.src = "jsplatformer1-smiley.jpg";
var canvas = null;
var context2D = null;
var left = false
var up = false
right = false
var down = false
window.onload = init;

function init()
{
	canvas = document.getElementById('canvas');
	context2D = canvas.getContext('2d');
	setInterval(draw, 1000 / FPS);
        document.addEventListener('keydown', draw, false);
}

function draw(event)
{
	context2D.clearRect(0, 0, canvas.width, canvas.height);
    	context2D.drawImage(image, x, y);

	if (event.keyCode == 39) {
	right=1;
	}
	if (right == true) {
	x+=1
	}	
}

One way to keep track of keys that are down is to create a whole separate object for it:


var isDown = {
    up: false,
    down: false,
    right: false,
    left: false
};

Then you can change those values to true or false on key up/down:


var keyCodes = {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down'
};

function keyCheck(e) {
    if (keyCodes[e.keyCode]) {
        isDown[keyCodes[e.keyCode]] = e.type === 'keydown' ? true : false;
    }
}

function init() {
    canvas = document.getElementById('canvas');
    context2D = canvas.getContext('2d');
    // note that there's no setInterval line here
    document.addEventListener('keydown', keyCheck, false);
    document.addEventListener('keyup', keyCheck, false);
}

But when it comes to actually moving the square on the canvas, you can go back to using setTimeout:


function draw() {
    if (isDown.up || isDown.down) {
        y += isDown.up ? -1 : 1;
    }
    if (isDown.left || isDown.right) {
        x += isDown.left ? -1 : 1;
    }
    context2D.clearRect(0, 0, canvas.width, canvas.height);
    context2D.drawImage(image, x, y);
    setTimeout(draw, 1000 / FPS);
}
draw(); // note that we call it immediately

That will constantly clear/redraw the square, even if its position hasn’t changed, so you could improve that a little (if you wanted to) by only redrawing if the x/y values were changed.