JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
JavaScript
gridRows = 10;
gridCols = 10;
tileSize = 40;
gridWidth = gridCols * tileSize;
gridHeight = gridRows * tileSize;
canvasWidth = tileSize * (gridCols + gridRows) * Math.sqrt(3) / 2;
canvasHeight = tileSize * (gridRows + gridCols) / 2;
canvasOffset = tileSize * gridRows * Math.sqrt(3) / 2;
function carToIso(x, y) {
// Convert cartesian (x, y) to isometric coordinates
return [
Math.round((x - y) * Math.sqrt(3) / 2 + canvasOffset),
Math.round((x + y) / 2)
];
}
function drawGrid() {
let canvas = $("#canvas");
canvas.attr('width', canvasWidth);
canvas.attr('height', canvasHeight);
let ctx = canvas.get(0).getContext('2d');
// Background
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
// Draw lines
ctx.beginPath();
ctx.lineWidth = 1;
// Rows
for(let i = 0; i <= gridRows; ++i) {
ctx.moveTo(...carToIso(0, i * tileSize));
ctx.lineTo(...carToIso(gridWidth, i * tileSize));
}
// Columns
for(let i = 0; i <= gridCols; ++i) {
ctx.moveTo(...carToIso(i * tileSize, 0));
ctx.lineTo(...carToIso(i * tileSize, gridHeight));
}
ctx.stroke();
}
drawGrid();