-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolygon.js
More file actions
58 lines (52 loc) · 1.38 KB
/
Polygon.js
File metadata and controls
58 lines (52 loc) · 1.38 KB
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
import { Rectangle } from "./Rectangle.js";
export class Polygon {
constructor(xpoints = [], ypoints = [], npoints = 0) {
this.xpoints = xpoints;
this.ypoints = ypoints;
this.npoints = npoints;
this.updateBounds();
}
copyPolygon() {
return new Polygon(this.xpoints, this.ypoints, this.npoints);
}
updateBounds() {
//calculate the bounds of the polygon
this.bounds = new Rectangle(
Math.min(...this.xpoints),
Math.min(...this.ypoints),
Math.max(...this.xpoints) - Math.min(...this.xpoints),
Math.max(...this.ypoints) - Math.min(...this.ypoints),
);
}
addPoint(xval, yval) {
this.xpoints.push(xval);
this.ypoints.push(yval);
this.npoints++;
this.updateBounds();
}
drawPolygon(context, color = null) {
if (color != null) {
context.strokeStyle = color;
}
context.lineWidth = 1;
context.beginPath();
context.moveTo(this.xpoints[0], this.ypoints[0]);
for (let i = 1; i < this.npoints; i++) {
context.lineTo(this.xpoints[i], this.ypoints[i]);
}
context.closePath();
context.stroke();
}
contains(x, y) {
// check if the x, y points are inside the rectangle
if (
this.bounds.x <= x &&
this.bounds.x + this.bounds.width >= x &&
this.bounds.y <= y &&
this.bounds.y + this.bounds.height >= y
) {
return true;
}
return false;
}
}