JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<canvas id="canvas" width="300" height="300"></canvas>
CSS
canvas { border:3px solid red; }
JavaScript
$(function() {
var x = 150,
y = 150,
dx = 2,
dy = 2,
canvas = $('#canvas'),
ctx = canvas[0].getContext('2d'),
width = canvas.width(),
height = canvas.height(),
keys = {},
intervalId = 0;
function circle(x, y, r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
$(document).keydown(function(e) { keys[e.which] = true; });
$(document).keyup(function(e) { keys[e.which] = false; });
intervalId = setInterval(function() {
ctx.clearRect(0, 0, width, height);
x = x - (keys['37'] ? dx : 0) + (keys['39'] ? dx : 0);
y = y - (keys['38'] ? dy : 0) + (keys['40'] ? dy : 0);
circle(x, y, 10);
}, 20);
});