JSFiddle - React, Tailwind, and code Playground

by rudiedirkx

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;

var object = {
    height: 40,
    width: 40,
    x: 10,
    y: 10, 
    color: "#FF0000"		
}

var dx = 0, dy = 0;
var speed = 100; // px per second

var activeKey = 0;
document.addEventListener('keydown', function(e) {
    if (activeKey == e.keyCode) return;
    activeKey = e.keyCode;
    
    //left
    if (e.keyCode == 37) {
        console.log('start moving LEFT');
        dx = -1;
    }
    //top
    else if (e.keyCode == 38) {
        console.log('start moving UP');
        dy = -1;
    }
    //right
    else if (e.keyCode == 39) {
        console.log('start moving RIGHT');
        dx = 1;
    }
    //bottom
    else if (e.keyCode == 40) {
        console.log('start moving DOWN');
        dy = 1;
    }
});
document.addEventListener('keyup', function(e) {
    switch (e.keyCode) {
        case 37: // left
        case 39: // right
            console.log('stop moving HOR');
            dx = 0;
            break;
            
        case 38: // up
        case 40: // down
            console.log('stop moving VER');
            dy = 0;
            break;
    }
    
    activeKey = 0;
});

function renderCanvas(){
    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, 600, 600);
} 
function renderObject(){
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(object.x, object.y, object.width, object.height);
}
function fun(){
    renderCanvas();
    
    object.x += dx / 60 * speed;
    object.y += dy / 60 * speed;
    renderObject();
    
    requestAnimationFrame(fun);
}

requestAnimationFrame(fun);