I am trying to make a basic game for training purposes in which the player could go either up, down, left or right. I have managed to print "x" on arrow key press to the direction it was pressed, but if I navigate to the left or down I'm not able to remove old prints.
I have tried many different combinations for left and down directions but i was not able to find how it is working.
What am i missing here ?
<canvas id="ctx" width="500" height="500" style="border:1px solid black">sss</canvas>
<script>
document.onkeydown = checkKey;
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
var HEIGHT = 500;
var WIDTH = 500;
var x = 50;
var y = 50;
var speed = 20;
ctx.fillText('x', x,y); // Writes text
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
console.log('up');
y-=speed;
ctx.clearRect(x,y, WIDTH, HEIGHT);
ctx.fillText('x', x,y); // Writes text
}
else if (e.keyCode == '40') {
// down arrow
console.log('down');
y+=speed;
ctx.fillText('x', x,y); // Writes text
}
else if (e.keyCode == '37') {
// left arrow
console.log('left');
x-=speed;
ctx.fillText('x', x,y); // Writes text
ctx.clearRect(x,y, WIDTH, HEIGHT);
}
else if (e.keyCode == '39') {
// right arrow
console.log('right');
x+=speed;
ctx.fillText('x', x,y); // Writes text
ctx.clearRect(x,y, -WIDTH, -HEIGHT);
}
}
</script>
How could I make "X" to navigate around the canvas without leaving old prints behind it ?
Thank you!