0

as you can see at https://codepen.io/anon/pen/PvZzpe the character is leaving a trail on pressing left and right keys

I am trying to make the character to move left and right on the screen without leaving a trail but it is not working

I am doing so by calling the clearBg() as here:https://codepen.io/anon/pen/dEGXjV

can you see what the problem is?

1 Answers1

0

The problem in your case is the clearBg function not work in a synchronous way. So when you click arrow keys it will first draw image and then clear the background. You will be able to solve that issue by using callback functions as below.

function clearBg(callback){
  var bg = new Image();
  bg.src = 'https://i.imgur.com/jfBz9o6.png';
  bg.onload = function(){ 
    c.drawImage(bg,0,0,950,550);
    if(callback) callback();
  };
}

function doKeyDown(event){
  switch(event.keyCode){
    case 37:
      clearBg(function() {
        MrK1.goLeft();
        MrK1.draw();
      });
      break;
    case 39:
      clearBg(function() {
        MrK1.goRight();
        MrK1.draw();
      });
      break;
  }
}

If you are not familiar with callbacks, just read this medium post. it will give you some basic idea.