JSFiddle - React, Tailwind, and code Playground

by techtiger255

HTML

<html>
<body>

<canvas width="480" height="340"></canvas>

</body>
</html>

CSS

canvas {
    background: #f2f2f2;
    border-radius: 5px;
}

JavaScript

const canvas = document.getElementsByTagName("canvas")[0],
    ctx = canvas.getContext("2d"),
    boundary = {
    	minimum: {x: -10, y: 0},
    	maximum: {x: 960, y: canvas.height - 5}
    };
    
let player = {
	x: 15,
    y: 15,
    w: 15,
    h: 15,
    draw: function() {
        color("red");
    this.x += this.speedX * player.LR;
    ctx.fillRect(this.x, this.y, this.w, this.h);
    },
    speedX: 5,
    soeedY: 0,
    LR: 0 // -1 = left, 0 = no movement, 1 = right0
},
paused = false;

function color(color = "gray") {
	ctx.fillStyle = color;
	return color;
}

function draw() {
	requestAnimationFrame(draw);
	if (paused) return;
    ctx.clearRect(0,0,canvas.width, canvas.height);

	player.draw();
}

draw();

window.addEventListener("keydown",keyPress);
window.addEventListener("keyup",keyPress);

function keyPress(e) {
	let affect = e.type.match(/down/) ? 1 : 0;
	switch (e.which) {
		case 37:
        // left
			player.LR = -1;
			break;
		case 38:
        // up
			player.speedY = 1;
			break;
		case 39:
        // right
			player.LR = 1;
			break;
		case 40:
        // down
			player.speedY = 1;
			break;
		default:
			return;
	}
}