bizzare putImageData action

44 Views Asked by At

Here is my code :

var ctx = document.getElementById("map").getContext("2d");
var ZeroX = 0;
var ZeroY = 0;
ctx.beginPath();
ctx.fillRect(100, 200, 100, 50); //Drawed a black rectangle

 function moveMap(evt) {
   var key = evt.keyCode || evt.which;
   if (key == 38) { //UP
     moveDirect(0, 20, false);
   }
   else if (key == 40) { //DOWN
     moveDirect(0, 20, true);
   }   
   else if (key == 39) { //RIGHT
     moveDirect(20, 0, true);
   }
   else if (key == 37) { //LEFT
     moveDirect(20, 0, false);
   }
 }
 
 function moveDirect(X, Y, minus) { 
   if (minus == false) {
     ZeroX -= X;
     ZeroY -= Y;  
   }
   else {
     ZeroX += X;
  ZeroY = Y; 
   }   
   var lol = ctx.getImageData(ZeroX, ZeroY, 3000, 3000);    
   ctx.clearRect(ZeroX, ZeroY, 3000, 3000);
   ctx.putImageData(lol, 0, 0);
 }
  <body onkeypress="moveMap(event)">
<canvas id="map" width="500" height="500">Map </canvas>
  </body>

  • If you run this snippet and click on one of the arrows on the keyboard, you'll see that the rectangle moves in the opposite direction because I wanted to make like the screen was a camera in a game. That's done on purpose

  • But if after you clicked on the arrow's oppsite (Up = Down, Left = Right, etc), you will see that you must click two times to make it move in the other direction. Try this with other arrows, still the same.

  • And if you press the same arrow many times, it's gap travelled becomes bigger and bigger, but logically it must the same.

I want it to respond directly, not on two clicks and that the gap is always the same. Please explain in your answer why this is happennings. Thaks beforehand!

0

There are 0 best solutions below