Skip to content

Instantly share code, notes, and snippets.

@Yumshot
Created March 27, 2023 15:58
Show Gist options
  • Save Yumshot/893e6f57a01e92440c9d523504c990b0 to your computer and use it in GitHub Desktop.
Save Yumshot/893e6f57a01e92440c9d523504c990b0 to your computer and use it in GitHub Desktop.
import { Delaunay } from 'd3-delaunay';
import './style.css';
const canvas = document.querySelector<HTMLCanvasElement>('#myCanvas')!
const ctx: CanvasRenderingContext2D | null = canvas.getContext("2d");
const pointsWanted = 5;
let points: ArrayLike<[number, number]> | Iterable<[number, number]> | any = [];
export function drawBoundingBox() {
if (!ctx) return;
const side = Math.min(canvas.width, canvas.height);
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = side / 2;
ctx.beginPath();
ctx.moveTo(centerX + radius, centerY);
for (let i = 1; i <= 7; i++) {
const angle = i * Math.PI / 4;
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
ctx.lineTo(x, y);
}
ctx.strokeStyle = 'white';
ctx.lineWidth = 0.7;
ctx.closePath();
ctx.stroke();
createRandomPoints();
}
export function createRandomPoints() {
if (!ctx) return;
const side = Math.min(canvas.width, canvas.height);
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = side / 2;
for (let index = 0; index < pointsWanted; index++) {
const angle = Math.random() * Math.PI * 2;
const r = Math.sqrt(Math.random()) * radius;
const x = centerX + r * Math.cos(angle);
const y = centerY + r * Math.sin(angle);
points.push([x, y])
if (points.length === pointsWanted) {
const delaunay: any = Delaunay.from(points);
drawPoints(delaunay);
}
}
}
const main = () => drawBoundingBox();
main();
function drawPoints(delaunay: { points: any; halfedges: any; triangles: any; }) {
if (!ctx) return;
const {points, triangles} = delaunay;
for (let index = 0; index < points.length; index++) {
const t0 = triangles[index * 3 + 0];
const t1 = triangles[index * 3 + 1];
const t2 = triangles[index * 3 + 2];
ctx.moveTo(points[t0 * 2], points[t0 * 2 + 1]);
ctx.lineTo(points[t1 * 2], points[t1 * 2 + 1]);
ctx.lineTo(points[t2 * 2], points[t2 * 2 + 1]);
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 0.7;
}
ctx.stroke();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment