2.5D orthographic tile map

2.5D orthographic tile map experiment

by Victor Ribeiro

HTML

<canvas id="bg"></canvas>
<canvas id="fg"></canvas>

<!-- https://www.linkedin.com/in/victorqribeiro //-->

CSS

body {
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
}

JavaScript

canvas = document.getElementById("bg");
canvas.width = w = innerWidth;
canvas.height = h = innerHeight;
bg = canvas.getContext("2d");
const ntiles = 8;
tileWidth = Math.floor(w/ntiles);
tileHeight = Math.floor(h/ntiles);

bg.translate(w/2,0);


for(let i = 0; i < ntiles; i++){
	for(let j = 0; j < ntiles; j++){
  	let h = Math.floor(Math.random() * 360);
  	drawTile(bg,i,j,'hsl('+h+',10%,50%)');
  }
}

function drawTile(c,x,y,color){
	c.save();
  c.translate((y-x) * tileWidth/2,(x+y)*tileHeight/2);
  c.beginPath();
  c.moveTo(0,0);
  c.lineTo(tileWidth/2,tileHeight/2);
  c.lineTo(0,tileHeight);
  c.lineTo(-tileWidth/2,tileHeight/2);
  c.closePath();
  c.fillStyle = color;
  c.fill();
  c.restore();
}

const fg = document.getElementById('fg');
fg.width = w;
fg.height = h;
const cf = fg.getContext('2d');

cf.translate(w/2,0);

const viz = function(e){
	let x = e.offsetX, y = e.offsetY;
  const _y = ( y / ( (ntiles * tileHeight) / ntiles ) );
  const _x = ( (x-tileWidth/2) / ( (ntiles * tileWidth) / ntiles ) )-ntiles/2;
  x = Math.round(_y-_x-1);
  y = Math.round(_x+_y);
  cf.clearRect(-w,-h,w*2,h*2);
  if( x >= 0 && x < ntiles && y >= 0 && y < ntiles){
    drawTile(cf,x,y,'red');
  }
}

fg.addEventListener('mousemove', viz );

fg.addEventListener('click', viz );