I am new to coding. And I am new to stack overflow. Please, please fogive me if I am not following any of the myriad of rules users have to follow around here.
I am trying to move an object on an HTML5 canvas using a javasript code. Instead, it keeps seeming to elongate. Do I have to use a clear function of some sort? When I do that, it seems to make the black square (player) disappear instead.
Here is my code. Any advice/suggestions would be helpful.
var c;
var ctx;
var playerPosX = 90;
var playerPosY = 90;
function init(){
c = document.getElementById("c");
ctx = c.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0,0,200,200);
setInterval (player, 10);
}
function player(){
c=document.getElementById("c");
ctx= c.getContext('2d');
ctx.fillStyle='black';
ctx.fillRect(playerPosX,playerPosY,20,20);
}
init();
function doKeyDown (evt){
switch (evt.keyCode) {
case 40:
playerPosY=playerPosY+1;
break;
}
}
document.addEventListener('keydown', doKeyDown, true);
<canvas id="c" width="300" height="300"></canvas>