JSFiddle - React, Tailwind, and code Playground

by mukkaram waheed

HTML

<!-- <img src="http://via.placeholder.com/350x150"> -->
<canvas id="myCanvas"  class="ball" width="200" height="100" style="border:1px solid #000000;">
</canvas>

CSS

.ball {
  width: 100px;
  height: 100px;
  position: absolute;
  left: 30px;
  top: 40px;
}

JavaScript

var change = {
  37: {
    left: "-=1"
  },

  38: {
    top: "-=1"
  },

  39: {
    left: "+=1"
  },

  40: {
    top: "+=1"
  },
}
$(document).one("keydown", keyDown)

var going;

function keyDown(e) {
  console.log("down")
  $(document).one("keyup", keyup)
  var animation = change[e.which];
  going = setInterval(keepGoing, 1);

  function keepGoing() {
    $(".ball").css(animation)
  }

}

function keyup(e) {
  console.log("up")
  clearInterval(going)
  $(document).one("keydown", keyDown)
}