mapRange
将一个数字在其所属范围内的相对位置映射到另一个范围内的等效位置。例如,在0到100的范围内,5050 处于中间位置,如果将其映射到0到500的范围,则结果为250(因为这是该范围的中间位置)。可以理解为比例。
另一个例子是一个宽度为200px的范围滑块——如果你希望用户可以拖动这个滑块(在0和200之间),以控制某个物体在屏幕上相应移动,当滑块位于最大值时,物体位于屏幕最右侧边缘;当滑块位于最小值时,物体位于屏幕最左侧边缘,这种情况下使用mapRange()非常合适。你将会把一个范围0-200映射到另一个范围0-window.innerWidth。
请选择以下方法签名之一——要么立即获取一个映射后的值,要么省略valueToMap
参数以获取一个可重复使用的函数,记住这些范围,这样你可以随后多次传入需要映射的值:
1) mapRange(inMin, inMax, outMin, outMax, valueToMap)
- inMin:数值 - 初始映射范围的下限
- inMax:数值 - 初始映射范围的上限
- outMin:数值 - 目标映射范围的下限
- outMax:数值 - 目标映射范围的上限
- valueToMap:数值 - 需要映射的值(通常在
inMin
和inMax
)。
返回: 映射后的数值
示例
//maps 0 in the -10 to 10 range to the same position in the 100 to 200 range
gsap.utils.mapRange(-10, 10, 100, 200, 0); // 150
// maps 50 in the range from 0 to 100 to the same position in the range from 0 to 500
gsap.utils.mapRange(0, 100, 0, 500, 50); // 250
2) mapRange(inMin, inMax, outMin, outMax)
- inMin:数值 - 初始映射范围的下限
- inMax:数值 - 初始映射范围的上限
- outMin:数值 - 目标映射范围的下限
- outMax:数值 - 目标映射范围的上限
返回: 一个可重复使用的函数,接受一个参数——需要映射的数值
如果你省略了valueToMap
(第五个)参数,该工具方法将返回一个可重复使用的函数函数,它已准备好根据最初提供的范围映射任意值。换句话说,返回的函数会记住输入/输出范围,因此它可以快速高效地在之后多次执行映射。
示例
// get a function that will always map between these ranges
var mapper = gsap.utils.mapRange(0, 100, 0, 250); //notice we didn't provide a valueToMap
// now we can reuse the function to map any values:
console.log(mapper(50)); // 125
console.log(mapper(10)); // 25
提示:组合使用多个可重复使用的函数实现强大的数据转换!
你可以pipe()
将几个可重复使用的函数限制范围, 映射到另一个范围,对齐, 插值,以及等等。例如:
// get a clamping function that will always clamp to a range between 0 and 100
var transformer = gsap.utils.pipe(
// clamp between 0 and 100
gsap.utils.clamp(0, 100),
// then map to the corresponding position on the width of the screen
gsap.utils.mapRange(0, 100, 0, window.innerWidth),
// then snap to the closest increment of 20
gsap.utils.snap(20)
);
// now we feed one value in and it gets run through ALL those transformations!:
transformer(25.874);