JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="100" height="100" style="border:1px solid #000000;"></canvas>
JavaScript
let cnt = 0;
const ctx = canvas.getContext('2d');
const player = {
x: 0,
y: 0
};
const xy = (x, y) => ({
x,
y
});
const dist = 40;
const objects = [
xy(0, 0),
xy(dist, 0),
xy(dist, dist),
xy(0, dist),
xy(-dist, dist),
xy(-dist, 0),
xy(-dist, -dist),
xy(0, -dist),
xy(dist, -dist),
]
function clamp(value, min, max){
if(value < min) return min;
else if(value > max) return max;
return value;
}
// yoinked from https://stackoverflow.com/questions/1828613/check-if-a-key-is-down
var pressedKeys = {};
window.onkeyup = function(e) { pressedKeys[e.keyCode] = false; }
window.onkeydown = function(e) { pressedKeys[e.keyCode] = true; }
function movePlayer() {
if(pressedKeys[37]){
player.x -= 2; //Left key
}
if(pressedKeys[38]){
player.y -= 2; //Up key
}
if(pressedKeys[39]){
player.x += 2; //Right key
}
if(pressedKeys[40]) {
player.y += 2; //Down key
}
}
window.addEventListener('keypress', movePlayer, false);
// the boudaries of your game world in pixels
const worldBounds = {minX:-100,maxX:100,minY:-100,maxY:100};
function draw() {
//clear the transformations and clear the canvas
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setTransform (if you are interested)
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// update the player position
movePlayer();
// player is clamped to the world boundaries - don't let the player leave
player.x = clamp(player.x, worldBounds.minX, worldBounds.maxX);
player.y = clamp(player.y, worldBounds.minY, worldBounds.maxY);
// center the camera aroud the player,
// but clamp the camera position (top left corner) to the world bounds
const camX = clamp(player.x - canvas.width/2, worldBounds.minX, worldBounds.maxX - canvas.width);
const camY = clamp(player.y - canvas.height/2, worldBounds.minY, worldBounds.maxY - canvas.height);
ctx.translate(-camX, -camY);
// draw...