snapsvg/src/lib/math.js

92 lines
2.0 KiB
JavaScript
Raw Normal View History

2024-03-06 18:36:03 +08:00
/**
* {数学相关}
* @author yutent<yutent.io@gmail.com>
* @date 2024/03/06 13:05:25
*/
/* -------------------------------------------------------- */
/* --------------------- 数学方法 ---------------------- */
/* -------------------------------------------------------- */
/**
* Returns an angle between two or three points
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
- x3 (number) #optional x coord of third point
- y3 (number) #optional y coord of third point
= (number) angle in degrees
*/
export function angle(x1, y1, x2, y2, x3, y3) {
if (x3 == null) {
let x = x1 - x2,
y = y1 - y2
if (!x && !y) {
return 0
}
return (180 + (Math.atan2(-y, -x) * 180) / Math.PI + 360) % 360
} else {
return angle(x1, y1, x3, y3) - angle(x2, y2, x3, y3)
}
}
export function rad(deg) {
return ((deg % 360) * Math.PI) / 180
}
export function deg(radius) {
return ((radius * 180) / Math.PI) % 360
}
export function sin(angle) {
return Math.sin(rad(angle))
}
export function tan(angle) {
return Math.tan(rad(angle))
}
export function cos(angle) {
return Math.cos(rad(angle))
}
export function asin(num) {
return deg(Math.asin(num))
}
export function acos(num) {
return deg(Math.acos(num))
}
export function atan(num) {
return deg(Math.atan(num))
}
export function atan2(x, y) {
return deg(Math.atan2(x, y))
}
/*\
**
* Returns distance between two points
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
\*/
export function len(x1, y1, x2, y2) {
return Math.sqrt(len2(x1, y1, x2, y2))
}
/*\
**
* Returns squared distance between two points
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
\*/
export function len2(x1, y1, x2, y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
}