-
Notifications
You must be signed in to change notification settings - Fork 16
/
svg.math.min.js
5 lines (5 loc) · 2.38 KB
/
svg.math.min.js
1
2
3
4
5
(function(){SVG.math={angle:function(a,b,c){if(c)return Math.abs(SVG.math.angle(a,c)-SVG.math.angle(b,c));for(a=Math.atan2(b.y-a.y,b.x-a.x);0>a;)a+=2*Math.PI;return a},rad:function(a){return a*Math.PI/180},deg:function(a){return 180*a/Math.PI},snapToAngle:function(a,b){var c=100,d,e,f;b.push(Math.min.apply(Math,b)+2*Math.PI);for(f=b.length;a>2*Math.PI;)a-=2*Math.PI;for(;0>a;)a+=2*Math.PI;for(e=0;e<f;e+=1){d=Math.abs(a-b[e]);if(d>c)return b[e-1];c=d}return b[0]},lerp:function(a,b,c){return a+c*(b-
a)}};SVG.math.Point=function(a,b){this.x=a;this.y=b};SVG.math.Point.attr={stroke:"#000",fill:"none",radius:5};SVG.extend(SVG.math.Point,{draw:function(a,b){if(a){attr=attr||SVG.math.Point.attr;var c=attr.radus||5;delete attr.radius;this.svg=a;this.circle=a.circle(c).attr(b)}else this.circle&&(this.circle.remove(),delete this.svg,delete this.circle);return this}});SVG.math.Line=function(a,b){this.update(a,b)};SVG.math.Line.attr={stroke:"#000",fill:"none"};SVG.extend(SVG.math.Line,{update:function(a,
b){this.p1=a;this.p2=b;this.a=this.p2.y-this.p1.y;this.b=this.p1.x-this.p2.x;this.c=a.x*b.y-b.x*a.y;return this},draw:function(a,b){a?(attr=attr||SVG.math.Line.attr,this.svg=a,this.line=a.line(p1.x,p1.y,p2.x,p2.y).attr(b)):this.line&&(this.line.remove(),delete this.svg,delete this.line);return this},parallel:function(a){return 0===this.a*a.b-a.a*this.b},move:function(a,b,c){var b=a.x>b.x?-1:a.x<b.x?1:a.y>b.y?-1:1,d=Math.atan(Math.abs(this.p1.y-this.p2.y)/Math.abs(this.p1.x-this.p2.x)),e=c*Math.sin(d),
c=c*Math.cos(d);return new SVG.math.Point(a.x+b*c,a.y+b*e)},intersection:function(a){var b=this.a*a.b-a.a*this.b;return{parallel:0===b,x:(a.b*this.c-this.b*a.c)/b,y:(this.a*a.c-a.a*this.c)/b}},midPoint:function(){return this.interpolatedPoint(0.5)},segmentLengthSquared:function(){var a=this.p2.x-this.p1.x,b=this.p2.y-this.p1.y;return a*a+b*b},closestLinearInterpolation:function(a){return((a.x-this.p1.x)*(this.p2.x-this.p1.x)+(a.y-this.p1.y)*(this.p2.y-this.p1.y))/this.segmentLengthSquared()},interpolatedPoint:function(a){return{x:SVG.math.lerp(this.p1.x,
this.p2.x,a),y:SVG.math.lerp(this.p1.y,this.p2.y,a)}},closestPoint:function(a){return this.interpolatedPoint(this.closestLinearInterpolation(a))},perpendicularLine:function(a,b){var c=this.p1.x-this.p2.x,d=this.p1.y-this.p2.y,e=Math.sqrt(c*c+d*d),c=c/e,d=d/e;return new SVG.math.Line(new SVG.math.Point(a.x+b*d,a.y-b*c),new SVG.math.Point(a.x-b*d,a.y+b*c))}})})();