Public
Edited
Sep 23, 2024
1 star
Insert cell
Insert cell
Insert cell
// Convert hex grid coordinates (i, j) to Cartesian coordinates (x, y)
function hexToCartesian(i, j, scale, centerX, centerY, sqrt3 = Math.sqrt(3)) {
const x = centerX + scale * (i + j * -0.5); // i determines x + offset by j
const y = centerY - scale * (j * sqrt3 / 2); // j determines y
return [x, y];
}
Insert cell
// Convert Cartesian coordinates (mouseX, mouseY) to approximate hex grid coordinates (i, j)
function cartesianToHex(mouseX, mouseY, scale, centerX, centerY, sqrt3 = Math.sqrt(3)) {
const j = Math.round((centerY - mouseY) / (scale * sqrt3 / 2)); // Calculate j from y-axis
const i = Math.round((mouseX - centerX - j * scale * -0.5) / scale); // Calculate i from x-axis
return { i, j }; // Return the nearest hex grid coordinates
}
Insert cell
// Function to find the nearest hex grid point to a given mouse position
function findNearestPoint(mouseX, mouseY, scale, centerX, centerY) {
const { i, j } = cartesianToHex(mouseX, mouseY, scale, centerX, centerY); // Get nearest hex grid coordinates
const [x, y] = hexToCartesian(i, j, scale, centerX, centerY); // Convert back to Cartesian for actual point position

return { x, y, i, j }; // Return both Cartesian and grid coordinates
}
Insert cell
polygonTemplates = ({
"turtle": [
[3, 0],
[2, 1],
[1, 2],
[-1, 1],
[-1, 2],
[-2, 2],
[-3, 0],
[-2, -1],
[-3, -2],
[-3, -3],
[-1, -2],
[0, -3],
[1, -2],
[2, -2]
],
"hat": [
[1, 0],
[2, 0],
[3, 1],
[2, 2],
[0, 1],
[0, 2],
[-1, 2],
[-2, 2],
[-3, 1],
[-2, 0],
[-3, -2],
[-2, -2],
[-2, -3],
[0, -2]
]
})
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more