StorymapperArrow/PolygonVisuals.js
2025-05-27 16:01:42 +02:00

45 lines
1.3 KiB
JavaScript

// Converts a Turf polygon into an array of canvas-compatible points
function toCanvasPolygon(turfPolygon) {
if (!turfPolygon || !turfPolygon.geometry) return [];
let polygons = [];
if (turfPolygon.geometry.type === 'Polygon') {
polygons.push(turfPolygon.geometry.coordinates[0]);
}
else if (turfPolygon.geometry.type === 'MultiPolygon') {
turfPolygon.geometry.coordinates.forEach(polygon => {
polygons.push(polygon[0]);
});
}
else {
console.error("Unsupported geometry type:", turfPolygon.geometry.type);
return [];
}
return polygons.map(coords =>
coords.slice(0, -1).map(coord => ({ x: coord[0], y: coord[1] }))
);
}
// Draws a polygon on the canvas with a given color
export function drawPolygon(turfPolygon, color, canvas) {
const ctx = canvas.getContext("2d");
ctx.fillStyle = color;
const polygons = toCanvasPolygon(turfPolygon);
if (!polygons.length) {
console.log("No valid polygons to draw.");
return;
}
polygons.forEach(points => {
if (points.length < 3) return;
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
points.forEach(p => ctx.lineTo(p.x, p.y));
ctx.closePath();
ctx.fill();
});
}