JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas"></canvas>
<div id="out">
dd
</div>
CSS
#out {
position: absolute;
z-index: 100;
top: 0;
font-size: 30px;
background: white;
}
JavaScript
let tile_entities = [
{x: 8, y: 0, w: 1, h: 4, id: "red"},
{x: 5, y: 0, w: 2, h: 1, id: "green"},
{x: 7, y: 0, w: 1, h: 1, id: "blue"},
{x: 3, y: 5, w: 6, h: 2, id: "yellow"},
]
let ctx = canvas.getContext("2d")
canvas.width = canvas.height = 400;
let size = {
x: 10,
y: 10
}
let camera = {
x: 10,
y: 10
}
let sizeX = (canvas.width / size.x),
sizeY = (canvas.height / size.y)
for (let y=0; y<size.y; y++) {
for (let x=0; x<size.x; x++) {
let posX = x * sizeX,
posY = y * sizeY;
ctx.strokeStyle = "red"
ctx.strokeRect(posX, posY, sizeX, sizeY);
}
}
let posX = camera.x * sizeX,
posY = camera.y * sizeY;
ctx.beginPath()
ctx.arc(posX-sizeX/2, posY-sizeX/2, sizeX/4, 0, 2*Math.PI)
ctx.fillStyle = "lightgreen"
ctx.fill()
for (let e=0; e<tile_entities.length; e++) {
let entity = tile_entities[e];
for (let y=entity.y; y<entity.y + entity.h; y++) {
for (let x=entity.x; x<entity.x + entity.w; x++) {
let posX = x * sizeX,
posY = y * sizeY;
ctx.fillStyle = entity.id//`hsl(${e * (360 / (tile_entities.length))}, 100%, 50%)`
ctx.fillRect(posX, posY, sizeX, sizeY);
}
}
}
let sorted = tile_entities.map(o => {
const xmin = o.x,
xmax = o.x + o.w,
ymin = o.y,
ymax = o.y + o.h;
const [closestX, farthestX] = [xmin, xmax].sort((a, b) => Math.abs(camera.x - a) - Math.abs(camera.x - b));
const [closestY, farthestY] = [ymin, ymax].sort((a, b) => Math.abs(camera.y - a) - Math.abs(camera.y - b));
return {
original: o,
x1: closestX,
y1: xmin <= camera.x && camera.x <= xmax ? closestY : farthestY,
x2: ymin <= camera.y && camera.y <= ymax ? closestX : farthestX,
y2: closestY
};
}).sort((a, b) => {
const camSegmentA1 = {
x1: camera.x,
y1: camera.y,
x2: a.x1,
y2: a.y1
};
const camSegmentA2 = {
x1: camera.x,
y1: camera.y,
x2: a.x2,
y2:...