https://github.com/w8r/liang-barsky
Liang-Barsky line-clipping algorithm
https://github.com/w8r/liang-barsky
algorithm clipping clipping-algorithm geometry
Last synced: about 1 month ago
JSON representation
Liang-Barsky line-clipping algorithm
- Host: GitHub
- URL: https://github.com/w8r/liang-barsky
- Owner: w8r
- License: mit
- Created: 2017-04-13T22:39:54.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2025-01-22T06:48:49.000Z (4 months ago)
- Last Synced: 2025-04-09T16:09:56.120Z (about 1 month ago)
- Topics: algorithm, clipping, clipping-algorithm, geometry
- Language: TypeScript
- Homepage: https://w8r.github.io/liang-barsky/
- Size: 2.09 MB
- Stars: 33
- Watchers: 0
- Forks: 1
- Open Issues: 6
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Liang-Barsky line-clipping algorithm [](https://www.npmjs.com/package/liang-barsky)

Fast, _destructive_ implemetation of [Liang-Barsky line clipping algorithm](https://en.wikipedia.org/wiki/Liang%E2%80%93Barsky_algorithm). It clips a 2D segment by a rectangle.
This is an adaptation of the [C++ code](http://hinjang.com/articles/04.html#eight)
that impressed me by its simplicity.## API
Destructive
```js
const a = [-10, -10],
b = [10, 10];
clip(a, b, [-5, -5, 5, 5]); // returns 1 - "clipped"
console.log(a); // [-5, -5]
console.log(b); // [5, 5]
```Non-destructive
```js
const a = [-10, -10],
b = [10, 10];
const an = a.slice(),
bn = b.slice();
clip(a, b, [-5, -5, 5, 5], an, bn); // returns 1 - "clipped"
console.log(an); // [-5, -5]
console.log(bn); // [5, 5]
console.log(a); // [-10, -10]
console.log(b); // [10, 10]
```Return value is `1` if the line was clipped, and `0` if it lies completely
outside of the provided bounding box.## Install
```
npm install -S liang-barsky
``````js
import { clip } from 'liang-barsky';
// or
var clip = require('liang-barsky');
```Or just drop-in the file
```html
liangBarsky.clip([0, 0], [10, 10], [0, 0, 5, 5]);
```
## Performance
I ran a check against the Cohen-Sutherland algorithm implemented by @mourner
for clipping just one segment. Though test include memory allocation, they are
fair for the task at hand, since you can use the results in an equal manner after
the invocation of the clipper.```
npm run benchmark
``````
liang-barsky x 112,058,856 ops/sec ±6.46% (87 runs sampled)
mapbox/lineclip x 27,754,592 ops/sec ±1.94% (98 runs sampled)
- Fastest is liang-barsky
```## Future plan
Implement a sub-routine for polylines. Loop through pairs, tracking in-out
transitions.## License
MIT