-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRectangle.js
More file actions
85 lines (73 loc) · 1.78 KB
/
Rectangle.js
File metadata and controls
85 lines (73 loc) · 1.78 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
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
export class Rectangle {
constructor(x = 0, y = 0, width = 0, height = 0) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
setBounds(x, y, width, height) {
this.setLocation(x, y);
this.setDimensions(width, height);
}
setLocation(x, y) {
this.x = x;
this.y = y;
}
setDimensions(width, height) {
this.width = width;
this.height = height;
}
reshape(x, y, width, height) {
this.setLocation(x, y);
this.setDimensions(width, height);
}
// check if there is any overlap between the two rectangles
intersects(rect2) {
// get the corners of the two rects
let lx1 = this.x;
let uy1 = this.y;
let rx1 = this.x + this.width;
let by1 = this.y + this.height;
let lx2 = rect2.x;
let uy2 = rect2.y;
let rx2 = rect2.x + rect2.width;
let by2 = rect2.y + rect2.height;
// upper left corner of the rect2 is within rect1
if (lx1 <= lx2 && lx2 <= rx1) {
if (uy1 <= uy2 && uy2 <= by1) {
return true;
}
}
// bottom right corner of the rect2 is within rect1
if (lx1 <= rx2 && rx2 <= rx1) {
if (uy1 <= by2 && by2 <= by1) {
return true;
}
}
// upper left corner of the rect1 is within rect2
if (lx2 <= lx1 && lx1 <= rx2) {
if (uy2 <= uy1 && uy1 <= by2) {
return true;
}
}
// bottom right corner of the rect1 is within rect2
if (lx2 <= rx1 && rx1 <= rx2) {
if (uy2 <= by1 && by1 <= by2) {
return true;
}
}
return false;
}
contains(x, y) {
// check if the x, y points are inside the rectangle
if (
this.x <= x &&
this.x + this.width >= x &&
this.y <= y &&
this.y + this.height >= y
) {
return true;
}
return false;
}
}