-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPoint.js
116 lines (101 loc) · 2.55 KB
/
Point.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/* exported Point */
"use strict";
function Point(x,y) {
this.x = x;
this.y = y;
}
Point.prototype.set = function(x,y) {
this.x = x;
this.y = y;
return this;
};
Point.prototype.copy = function(point) {
if (! (point instanceof Point)) {
throw "intance of Point expected";
}
this.x = point.x;
this.y = point.y;
return this;
};
Point.prototype.clone = function() {
return new Point(this.x,this.y);
};
Point.prototype.offset = function(point) {
if (! (point instanceof Point)) {
throw "intance of Point expected";
}
this.x += point.x;
this.y += point.y;
return this;
};
Point.prototype.negOffset = function(point) {
if (! (point instanceof Point)) {
throw "intance of Point expected";
}
this.x -= point.x;
this.y -= point.y;
return this;
};
Point.prototype.add = function(point) {
if (! (point instanceof Point)) {
throw "intance of Point expected";
}
return new Point( this.x + point.x,
this.y + point.y );
};
Point.prototype.sub = function(point) {
if (! (point instanceof Point)) {
throw "intance of Point expected";
}
return new Point( this.x - point.x,
this.y - point.y );
};
Point.prototype.isEqualTo = function(point) {
if (! (point instanceof Point)) {
throw "intance of Point expected";
}
var epsilon = 0.000000000001; // floating point approximation
return this.x > point.x-epsilon &&
this.x < point.x+epsilon &&
this.y > point.y-epsilon &&
this.y < point.y+epsilon;
};
Point.prototype.scale = function (factor) {
this.x *= factor;
this.y *= factor;
return this;
};
Point.prototype.invScale = function (factor) {
if (factor === 0) {throw "divide by zero attempt";}
this.x /= factor;
this.y /= factor;
return this;
};
Point.prototype.multiplyBy = function (factor) {
return new Point(this.x * factor, this.y * factor);
};
Point.prototype.divideBy = function (factor) {
if (factor === 0) {throw "divide by zero attempt";}
return new Point(this.x / factor, this.y / factor);
};
Point.prototype.half = function () {
return new Point(this.x/2, this.y/2);
};
Point.prototype.minus = function () {
return new Point(-this.x, -this.y);
};
Point.prototype.toString = function() {
return '('+this.x+','+this.y+')';
};
Point.prototype.distanceToSquared = function(point) {
return (
(this.x-point.x) * (this.x-point.x) +
(this.y-point.y) * (this.y-point.y)
);
};
Point.prototype.distanceTo = function(point) {
return Math.sqrt(this.distanceToSquared(point));
};
Point.prototype.angleTo = function(point) {
return Math.atan2(point.y-this.y,point.x-this.x);
};