cross-gesture
Version:
Gesture lib for the modern browsers
55 lines • 2.1 kB
JavaScript
import { SwipeDirection } from './types';
export function vectorAbs(v) {
return Math.sqrt(v.x * v.x + v.y * v.y);
}
export function vectorDot(f, t) {
return f.x * t.x + f.y * t.y;
}
// 返回缩放的倍数
export function pinchTimes(from, to) {
const fromLen = Math.sqrt(Math.pow(Math.abs(from[0].x - from[1].x), 2) + Math.pow(Math.abs(from[0].y - from[1].y), 2));
const toLen = Math.sqrt(Math.pow(Math.abs(to[0].x - to[1].x), 2) + Math.pow(Math.abs(to[0].y - to[1].y), 2));
return toLen / fromLen;
}
// 返回旋转的角度
// 顺时针为正数
export function getRotateDeg(from, to) {
const fromVector = { x: from[1].x - from[0].x, y: from[1].y - from[0].y };
const toVector = { x: to[1].x - to[0].x, y: to[1].y - to[0].y };
// direction: https://blog.csdn.net/qq_42778110/article/details/81567954
const direction = fromVector.x * toVector.y - fromVector.y * toVector.x;
if (direction === 0) {
return 0;
}
// a * b = |a|*|b|*cos(deg)
// cos(deg) = (a * b) / (|a| * |b|)
const cosDeg = vectorDot(fromVector, toVector) / (vectorAbs(fromVector) * vectorAbs(toVector));
return (direction > 0 ? 1 : -1) * Math.acos(cosDeg);
}
// 返回滑动反向和速度
export function getDirectionAndSpeed(from, to, duration) {
const distanceX = to.x - from.x;
const distanceY = to.y - from.y;
return {
vDirection: distanceX > 0 ? SwipeDirection.right : SwipeDirection.left,
vSpeed: distanceX / duration,
hDirection: distanceY > 0 ? SwipeDirection.bottom : SwipeDirection.top,
hSpeed: distanceY / duration,
};
}
export function getCrossPoint(from, to) {
// k = (y2 - y1) / (x2 - x1)
// b = y1 - k * x1
const k1 = (from[1].y - from[0].y) / (from[1].x - from[0].x);
const b1 = from[0].y - k1 * from[0].x;
const k2 = (to[1].y - to[0].y) / (to[1].x - to[0].x);
const b2 = to[0].y - k2 * to[0].x;
// x = (b1 - b2) / (k2 - k1)
// y = k1x + b1
const x = (b1 - b2) / (k2 - k1);
return {
x,
y: k1 * x + b1,
};
}
//# sourceMappingURL=utils.js.map