-
Notifications
You must be signed in to change notification settings - Fork 0
/
polygon.js
executable file
·91 lines (72 loc) · 2.26 KB
/
polygon.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
function Polygon (points, fillcolor, stokecolor) {
this.points = points;
this.center = new Point(0, 0);
this.fillcolor = fillcolor || '#555555';
this.strokecolor = stokecolor || '#252525';
this.updateCenter();
}
Polygon.prototype.render = function(ctx, fill, stroke) {
// polygon path
ctx.beginPath();
ctx.moveTo(this.points[0].x, this.points[0].y);
for (var i = 1; i < this.points.length; i++) {
ctx.lineTo(this.points[i].x, this.points[i].y);
}
ctx.lineTo(this.points[0].x, this.points[0].y);
ctx.closePath();
// fill
ctx.fillStyle = this.fillcolor || fill;
ctx.fill();
// stroke
ctx.strokeStyle = this.strokecolor || stroke;
ctx.stroke();
};
Polygon.prototype.updateCenter = function() {
// zurücksetzen
this.center.positionAt(0, 0);
// alle Punkte durchlaufen
for (var i = 0; i < this.points.length; i++) {
this.center.add(this.points[i].x, this.points[i].y);
}
// mitteln
this.center.multiply(1 / this.points.length);
};
Polygon.prototype.positionAt = function(x, y) {
// vector zwischen (x,y) und zentrum berechnen
var vx = x - this.center.x;
var vy = y - this.center.y;
// alle punkte um diesen vector verschieben
for (var i = 0; i < this.points.length; i++) {
this.points[i].add(vx, vy);
}
// Zentrum neu berechnen
this.center.add(vx, vy);
};
Polygon.prototype.move = function(x, y) {
// alle punkte um diesen vector verschieben
for (var i=0; i<this.points.length; i++) {
this.points[i].add(x, y);
}
// Zentrum neu berechnen
this.center.add(x, y);
};
Polygon.prototype.getMaxDistanceToPoint = function(point) {
var maxDistance = 0;
for (var i = 0; i < this.points.length; i++) {
var distance = this.points[i].distance_to(point.x, point.y);
if (distance >= maxDistance) {
maxDistance = distance;
}
}
return maxDistance;
};
Polygon.prototype.getMinDistanceToPoint = function(point) {
var minDistance = 10000;
for (var i = 0; i < this.points.length; i++) {
var distance = this.points[i].distance_to(point.x, point.y);
if (distance <= minDistance) {
minDistance = distance;
}
}
return minDistance;
};