JSFiddle - React, Tailwind, and code Playground
by frogggeee McFrogggeee
HTML
<!DOCTYPE html>
<html>
<head>
<body>
<canvas id = "canvas" width = "500" height = "500"></canvas>
<script>
let ctx = document.getElementById("canvas").getContext("2d");
let hx = 150;
let hy = 150;
let ax = 300;
let ay = 150;
let tX = [];
let tY = [];
let mx = 0;
let my = 0;
let TL = 5;
let speed = 20
let pressed = 0;
document.addEventListener("keydown", function(e) {
pressed = e.keyCode;
});
function text(t, x, y, px, c) {
ctx.beginPath();
ctx.font = px + "px Roboto Mono";
ctx.fillStyle = c;
ctx.fillText(t, x, y);
ctx.closePath();
}
function block(x, y, w, h, c) {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.fillStyle = c;
ctx.fill();
ctx.closePath();
}
function render() {
ctx.clearRect(0, 0, 500, 500);
block(0, 0, 500, 500, "black");
if (pressed == 39 || pressed == 68) {
mx = speed;
my = 0;
}
if (pressed == 37 || pressed == 82) {
mx = speed / -1;
my = 0;
}
if (pressed == 40 || pressed == 83) {
my = speed;
mx = 0;
}
if (pressed == 38 || pressed == 87) {
my = speed / -1;
mx = 0;
}
tX.push(hx);
tY.push(hy);
if (tX.length > TL) {
tX.shift();
tY.shift();
}
hx += mx;
hy += my;
if (hx < 0) {
hx = 500;
} else if (hx > 500) {
hx = 0;
}
if (hy < 0) {
hy = 500;
} else if (hy > 500) {
hy = 0;
}
block(hx, hy, 20, 20, "purple");
for (let i = 0; i < TL; i++) {
block(tX[i], tY[i], 20, 20, "blue");
}
block(ax + 2, ay + 2, 16, 16, "red");
}
setInterval(render, 10);
</script>
</body>
</head>
</html>