JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="400" height="200"></canvas>
JavaScript
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext("2d");
var player = {
color: "black",
x: 0,
y: 60,
w: 10,
h: 10
}
var kc;
document.addEventListener('keydown', function(e) {
kc = e.keyCode;
console.log(kc);
}, false);
document.addEventListener('keyup', function(e) {
kc = false;
}, false);
function update() {
switch (kc) {
case 37:
player.x -= 2;
break;
case 39:
player.x += 2;
break;
case 38:
var height = 3;
player.y -= height;
returnDown(height);
break;
}
}
function draw() {
ctx.clearRect(0, 0, 800, 600);
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.w, player.h);
update();
window.requestAnimationFrame(draw);
}
draw();
function returnDown(val) {
setTimeout(function(e) {
player.y += val;
}, 300);
}