Create utils.js
Browse files
utils.js
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
function lerp(a,b,t){
|
2 |
+
return a+(b-a)*t;
|
3 |
+
}
|
4 |
+
|
5 |
+
function getIntersection(A,B,C,D){
|
6 |
+
const tTop=(D.x-C.x)*(A.y-C.y)-(D.y-C.y)*(A.x-C.x);
|
7 |
+
const uTop=(C.y-A.y)*(A.x-B.x)-(C.x-A.x)*(A.y-B.y);
|
8 |
+
const bottom=(D.y-C.y)*(B.x-A.x)-(D.x-C.x)*(B.y-A.y);
|
9 |
+
|
10 |
+
if(bottom!=0){
|
11 |
+
const t=tTop/bottom;
|
12 |
+
const u=uTop/bottom;
|
13 |
+
if(t>=0 && t<=1 && u>=0 && u<=1){
|
14 |
+
return {
|
15 |
+
x:lerp(A.x,B.x,t),
|
16 |
+
y:lerp(A.y,B.y,t),
|
17 |
+
offset:t
|
18 |
+
}
|
19 |
+
}
|
20 |
+
}
|
21 |
+
|
22 |
+
return null;
|
23 |
+
}
|
24 |
+
|
25 |
+
//polylines
|
26 |
+
function polysIntersect(poly1, poly2){
|
27 |
+
for(let i=0;i<poly1.length-1;i++){
|
28 |
+
for(let j=0;j<poly2.length-1;j++){
|
29 |
+
const touch=getIntersection(
|
30 |
+
poly1[i],
|
31 |
+
poly1[i+1],
|
32 |
+
poly2[j],
|
33 |
+
poly2[j+1]
|
34 |
+
);
|
35 |
+
if(touch){
|
36 |
+
return true;
|
37 |
+
}
|
38 |
+
}
|
39 |
+
}
|
40 |
+
return false;
|
41 |
+
}
|
42 |
+
|
43 |
+
function getRGBA(value){
|
44 |
+
const alpha=Math.abs(value);
|
45 |
+
const R=value<0?0:255;
|
46 |
+
const G=R;
|
47 |
+
const B=value>0?0:255;
|
48 |
+
return "rgba("+R+","+G+","+B+","+alpha+")";
|
49 |
+
}
|