7 lines
1.7 KiB
JavaScript
7 lines
1.7 KiB
JavaScript
|
/**
|
||
|
* Graham's Scan Convex Hull Algorithm
|
||
|
* Author: Brian Barnett, brian@3kb.co.uk, http://brianbar.net/ || http://3kb.co.uk/
|
||
|
* Date: 14/06/13
|
||
|
* Updated: 25/01/14
|
||
|
* Description: An implementation of the Graham's Scan Convex Hull algorithm in Javascript.*/
|
||
|
function ConvexHullGrahamScan(){this.anchorPoint=undefined;this.reverse=false;this.points=[]}ConvexHullGrahamScan.prototype={constructor:ConvexHullGrahamScan,Point:function(e,t){this.x=e;this.y=t},_findPolarAngle:function(e,t){var n=57.295779513082;var r=t.x-e.x;var i=t.y-e.y;if(r==0&&i==0){return 0}var s=Math.atan2(i,r)*n;if(this.reverse){if(s<=0){s+=360}}else{if(s>=0){s+=360}}return s},addPoint:function(e,t){if(this.anchorPoint===undefined){this.anchorPoint=new this.Point(e,t)}else if(this.anchorPoint.y>t||this.anchorPoint.y==t&&this.anchorPoint.x>e){this.anchorPoint.y=t;this.anchorPoint.x=e;this.points.unshift(new this.Point(e,t));return}this.points.push(new this.Point(e,t))},_sortPoints:function(){var e=this;return this.points.sort(function(t,n){var r=e._findPolarAngle(e.anchorPoint,t);var i=e._findPolarAngle(e.anchorPoint,n);if(r<i){return-1}if(r>i){return 1}return 0})},_checkPoints:function(e,t,n){var r;var i=this._findPolarAngle(e,t);var s=this._findPolarAngle(e,n);if(i>s){r=i-s;return!(r>180)}else if(i<s){r=s-i;return r>180}return false},getHull:function(){var e=[],t,n;this.reverse=this.points.every(function(e){return e.x<0&&e.y<0});t=this._sortPoints();n=t.length;if(n<4){return t}e.push(t.shift(),t.shift());while(true){var r,i,s;e.push(t.shift());r=e[e.length-3];i=e[e.length-2];s=e[e.length-1];if(this._checkPoints(r,i,s)){e.splice(e.length-2,1)}if(t.length==0){if(n==e.length){return e}t=e;n=t.length;e=[];e.push(t.shift(),t.shift())}}}}
|