Greiner-Hormann clipping algorithm
The algorithm is a rough implementation of Gunther Greiner and Kai Hormann "Efficient Clipping of Arbitrary Polygons". You can use it in browser or node.
- Does AND, OR, XOR (intersection, union, difference, if you're human)
- Plays nicely with Leaflet, comes with an adaptor for it
- Handles non-convex polygons and multiple clipping areas
- ~4kb compressed, no dependencies
- Written in TypeScript with full type definitions
Examples
AND (Intersection)
OR (union)
XOR (diff)
Usage
npm
$ npm install greiner-hormann
ES Modules (Recommended)
import { intersection, union, diff } from 'greiner-hormann';
const polygon1 = [[0, 0], [100, 0], [100, 100], [0, 100]];
const polygon2 = [[50, 50], [150, 50], [150, 150], [50, 150]];
const result = intersection(polygon1, polygon2);
Browser (UMD)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/leaflet.umd.js"></script>
<script>
// The library is available as greinerHormann global
const result = greinerHormann.intersection(sourcePolygon, clipPolygon);
// With Leaflet polygons
if (result) {
if (Array.isArray(result[0])) {
L.polygon(result, { color: 'red' }).addTo(map);
} else {
result.forEach(poly => L.polygon(poly, { color: 'red' }).addTo(map));
}
}
</script>
Results
The output of the binary operation could be one or several linear
rings, or null. Always check the result before using
it.
TypeScript Support
The library is written in TypeScript and includes full type definitions. Import and use with full type safety:
import { intersection, union, diff } from 'greiner-hormann';
type Point = [number, number] | { x: number; y: number };
type Polygon = Point[];
const result: Polygon[] | null = intersection(polygon1, polygon2);
License
(The MIT License)
Copyright (c) 2014-2026 Alexander Milevski [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.