方向性吸附。
通常当你捕捉一个值时,它会跳转到最近的那一个(要么是一个增量,要么是数组中的值),例如:
let snap = gsap.utils.snap(5); // returns a function that snaps any value to the closest increment of 5
console.log(snap(2)); // 0
console.log(snap(3.5)); // 5
console.log(snap(19)); // 20
但是如果你希望应用这样的捕捉功能呢?比如说,你想捕捉到比当前值大的、最接近的那个5的倍数?directional你需要一个能够接受值和方向的函数,其中1
表示“更大”,而-1
表示“更小”。以下是这个辅助函数:
function getDirectionalSnapFunc(snapIncrementOrArray) {
let snap = gsap.utils.snap(snapIncrementOrArray),
a =
Array.isArray(snapIncrementOrArray) &&
snapIncrementOrArray.slice(0).sort((a, b) => a - b);
return a
? (value, direction) => {
let i;
if (!direction) {
return snap(value);
}
if (direction > 0) {
value -= 1e-4; // to avoid rounding errors. If we're too strict, it might snap forward, then immediately again, and again.
for (i = 0; i < a.length; i++) {
if (a[i] >= value) {
return a[i];
}
}
return a[i - 1];
} else {
i = a.length;
value += 1e-4;
while (i--) {
if (a[i] <= value) {
return a[i];
}
}
}
return a[0];
}
: (value, direction) => {
let snapped = snap(value);
return !direction ||
Math.abs(snapped - value) < 0.001 ||
snapped - value < 0 === direction < 0
? snapped
: snap(
direction < 0
? value - snapIncrementOrArray
: value + snapIncrementOrArray
);
};
}
用法
let snap = getDirectionalSnapFunc(5); // returns a function that snaps any value to the closest increment of 5 in a particular direction
console.log(snap(2, 1)); // 5
console.log(snap(3.5, -1)); // 0
console.log(snap(19, -1)); // 15
注意你可以使用一个值的数组来替代增量,非常方便!