diff --git a/src/polygon.ts b/src/polygon.ts index 7f4473c..9596f71 100755 --- a/src/polygon.ts +++ b/src/polygon.ts @@ -135,6 +135,12 @@ export class Polygon implements GeoShape { return new Polygon(...points); } + /** Creates a polygon from a shape. */ + static from(shape: GeoShape, resolution = 60): Polygon { + const points = tabulate((i) => shape.at(i / resolution), resolution); + return new Polygon(...points); + } + /** Interpolates the points of two polygons */ static interpolate(p1: Polygon, p2: Polygon, t = 0.5) { // TODO support interpolating polygons with different numbers of points diff --git a/test/polygon-test.ts b/test/polygon-test.ts index 11fafff..09a30b3 100644 --- a/test/polygon-test.ts +++ b/test/polygon-test.ts @@ -5,7 +5,7 @@ import tape from 'tape'; -import {Line, Point, Polygon, Polyline} from '../src'; +import {Circle, Line, Point, Polygon, Polyline} from '../src'; const poly = (...p: number[][]) => new Polygon(...p.map(q => new Point(q[0], q[1]))); @@ -52,3 +52,11 @@ tape('Cutting', (test) => { test.end(); }); + +tape('From', (test) => { + const circle = new Circle(new Point(0, 0), 1); + const p = points(Polygon.from(circle, 4)); + test.deepEqual(p, [[1, 0], [6.123233995736766e-17, 1], [-1, 1.2246467991473532e-16], [-1.8369701987210297e-16, -1]]); + + test.end(); +})