JSFiddle - React, Tailwind, and code Playground
by darthdeus
HTML
<canvas id="canvas" height="200" width="200" tabindex="1"></canvas>
JavaScript
var lastFrame = performance.now();
var requestAnimationFrameId;
var FPS = 1;
var alpha = 0.1;
function stopGameLoop() {
window.cancelAnimationFrame(requestAnimationFrameId);
}
function gameLoop(timestamp) {
requestAnimationFrameId = window.requestAnimationFrame(gameLoop);
if (timestamp < lastFrame + (1000 / 60)) {
return;
}
var dt = (timestamp - lastFrame) / 1000;
lastFrame = timestamp;
FPS = FPS + (1 - alpha) * (1/dt - FPS);
updatePlayer(dt);
drawMap();
drawPlayer();
}
requestAnimationFrameId = window.requestAnimationFrame(gameLoop);
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var BOX_SIZE = 20;
var MAP_W = 10;
var MAP_H = 10;
function drawBox(color, x, y, w, h) {
ctx.fillStyle = color;
ctx.fillRect(x, y, w || BOX_SIZE, h || BOX_SIZE);
}
var map = [
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,1,1,1,0,0,0,0,
0,0,0,0,0,0,0,0,1,1,
1,0,0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,0,1,1,1,1,
1,1,1,1,1,0,1,1,1,1,
];
function drawMap() {
for (var i = 0; i < MAP_H; i++) {
for (var j = 0; j < MAP_W; j++) {
var color = map[i * MAP_W + j] ? "#5d995d" : "lightblue";
drawBox(color, BOX_SIZE * j, BOX_SIZE * i);
}
}
}
var keys = {};
window.onkeyup = function(e) { delete keys[e.keyCode] }
window.onkeydown = function(e) { keys[e.keyCode] = true; }
var player = { x: 0, y: 0 };
function drawPlayer() {
drawBox("#612b2e", player.x, player.y);
}
function updatePlayer(dt) {
// Key codes for player hotkeys.
var A = 65;
var W = 87;
var D = 68;
// The player moves at 80px per second.
var SPEED = 80;
if (keys[A]) { player.x -= SPEED * dt; }
if (keys[D]) { player.x += SPEED * dt; }
}