Skip to content

Instantly share code, notes, and snippets.

@Yumshot
Created March 27, 2023 16:00
Show Gist options
  • Save Yumshot/600c05b956c57eb4a3511858bee7a922 to your computer and use it in GitHub Desktop.
Save Yumshot/600c05b956c57eb4a3511858bee7a922 to your computer and use it in GitHub Desktop.
export function drawSquareGridPattern(ctx: CanvasRenderingContext2D, width: number, height: number) {
// Generate a random set of points
const numPoints = Math.floor(Math.random() * 20) + 10;
const points = range(numPoints).map(() => [Math.random() * width, Math.random() * height] as [number, number]);
// Create a Voronoi diagram from the points
const voronoiDiagram = voronoi().extent([[0, 0], [width, height]])(points);
// Find the four outermost edges of the Voronoi diagram
let topEdge: any, bottomEdge: any, leftEdge: any, rightEdge: any;
voronoiDiagram.edges.forEach((edge: { left: any; right: any; }) => {
const start = edge.left;
const end = edge.right;
if (!start || !end) return;
if (start[1] === 0 && end[1] === 0) topEdge = [start, end];
if (start[1] === height && end[1] === height) bottomEdge = [start, end];
if (start[0] === 0 && end[0] === 0) leftEdge = [start, end];
if (start[0] === width && end[0] === width) rightEdge = [start, end];
});
// Extend the outer edges to form a square boundary
const boundary = [
topEdge && topEdge[0],
leftEdge && leftEdge[0],
bottomEdge && bottomEdge[0],
rightEdge && rightEdge[0],
];
// Draw the boundary
ctx.strokeStyle = "red";
ctx.lineWidth = 4;
ctx.beginPath();
boundary.forEach((point: [number, number]) => {
if (point) {
ctx.lineTo(point[0], point[1]);
}
});
ctx.stroke();
// Calculate the size of each square in the grid
const gridSize = Math.min(width, height) / 10;
// Draw the grid
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
ctx.beginPath();
for (let x = gridSize; x < width; x += gridSize) {
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
}
for (let y = gridSize; y < height; y += gridSize) {
ctx.moveTo(0, y);
ctx.lineTo(width, y);
}
ctx.stroke();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment