I have an isometric grid I'm drawing on a canvas. It uses a 30 degree angle offset and I use some script to draw a basic grid. For this grid I am projecting a flat grid with 40x40 tile sizes.
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();
This works perfectly fine and gets me the grid I want. A fiddle with this working is here; https://jsfiddle.net/fgw10sev/2/
For the next step, I need to figure out what tile someone is hovering over. I initially had a 2:1 grid and was able to convert mouse coordinates within the canvas to grid coordinates in the original un-projected grid like so;
function mouseToIso(x, y) {
// Convert mouse (x, y in canvas) to grid coordinates
return [
Math.round((2 * y + x - canvasOffset) / 2),
Math.round((2 * y - x + canvasOffset) / 2)
];
}
However, with the addition of the sqrt(3) factor, this no longer works and I cannot - for the life of me - figure out how to fix this. The original mouseToIso function was already a hackjob of trial and error and I've tried injecting the sqrt(3) factor in various places, but I just can't get it to work.
Can anyone help me out here? Or tell me I need to use a completely different approach entirely?
Note; I need this sqrt(3) factor in there because of the images I'm using. They're all at 30 degree angles and without that factor, the grid does no line up properly with the images.
Note 2; just for completenes - sqrt(3)/2 == cos(deg2rad(30)) and the 2 can be used interchangeably.