JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="c" width="400" height="400"></canvas>
JavaScript
// (0, 0) is at the top of the diamond. This is where we'll start drawing
sourceX = 200;
sourceY = 20;
// How much we move on the X axis for each tile
tileWidth = 30;
// How much we move on the Y axis for each tile
tileHeight = 15;
// How much we move on the Y axis for each unit of depth
tileDepth = 10;
// The size of the field, and the field itself
width = 5;
height = 5;
depths = [
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 2, 2, 2],
[0, 0, 2, 3, 1],
[0, 0, 0, 1, 2]
];
function getDepth(x, y)
{
// Wrap to the borders
if (x < 0)
x = 0;
else if (x >= width)
x = width - 1;
if (y < 0)
y = 0;
else if (y >= height)
y = height - 1;
return depths[y][x];
}
function getDrawingPos(x, y)
{
// Get the drawing position for a given point
var destX = sourceX - ((x - y) * tileWidth);
var destY = sourceY + ((x + y) * tileHeight) - (tileDepth * getDepth(x, y));
return {"x": destX, "y": destY};
}
function drawDiamond(ctx, x, y)
{
// Just find the points for all the corners..
var point0 = getDrawingPos(x, y);
var point1 = getDrawingPos(x + 1, y);
var point2 = getDrawingPos(x + 1, y + 1);
var point3 = getDrawingPos(x, y + 1);
ctx.beginPath();
// And draw them
ctx.moveTo(point0.x, point0.y);
ctx.lineTo(point1.x, point1.y);
ctx.lineTo(point2.x, point2.y);
ctx.lineTo(point3.x, point3.y);
ctx.lineTo(point0.x, point0.y);
ctx.stroke();
ctx.fill();
};
function drawField(ctx)
{
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
drawDiamond(ctx, x, y);
}
}
}
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
ctx.mozImageSmoothingEnabled = false;
ctx.fillStyle = 'rgba(50, 50, 50, 0.5)';
ctx.strokeStyle = 'rgba(255, 50, 50, 0.5)';
drawField(ctx);