gsap-utils
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesegsap.utils
gsap.utils
When to Use This Skill
何时使用该技能
Apply when writing or reviewing code that uses gsap.utils for math, array/collection handling, unit parsing, or value mapping in animations (e.g. mapping scroll to a value, randomizing, snapping to a grid, or normalizing inputs).
Related skills: Use with gsap-core, gsap-timeline, and gsap-scrolltrigger when building animations; CustomEase and other easing utilities are in gsap-plugins.
在编写或审查使用gsap.utils处理动画中的数学运算、数组/集合操作、单位解析或值映射(例如将滚动位置映射为某个值、随机化、对齐网格或归一化输入)的代码时使用。
相关技能: 构建动画时可搭配gsap-core、gsap-timeline和gsap-scrolltrigger使用;CustomEase及其他缓动工具属于gsap-plugins。
Overview
概述
gsap.utils provides pure helpers; no need to register. Use in tween vars (e.g. function-based values), in ScrollTrigger or Observer callbacks, or in any JS that drives GSAP. All are on gsap.utils (e.g. ).
gsap.utils.clamp()Omitting the value: function form. Many utils accept the value to transform as the last argument. If you omit that argument, the util returns a function that accepts the value later. Use the function form when you need to clamp, map, normalize, or snap many values with the same config (e.g. in a mousemove handler or tween callback). Exception: random() — pass true as the last argument to get a reusable function (do not omit the value); see random().
javascript
// With value: returns the result
gsap.utils.clamp(0, 100, 150); // 100
// Without value: returns a function you call with the value later
let c = gsap.utils.clamp(0, 100);
c(150); // 100
c(-10); // 0gsap.utils提供纯辅助函数,无需注册即可使用。可在补间变量(例如基于函数的值)、ScrollTrigger或Observer回调中使用,也可用于任何驱动GSAP的JS代码。所有方法都挂载在gsap.utils下(例如 )。
gsap.utils.clamp()省略值:函数形式。 许多工具函数接受要转换的值作为最后一个参数。如果省略该参数,工具会返回一个函数,后续可传入值进行调用。当你需要使用相同范围/配置对多个值进行限制、映射、归一化或对齐操作时(例如在鼠标移动处理器或补间回调中),可使用函数形式。例外:random() —— 需传入true作为最后一个参数来获取可复用函数(不能省略值);详情请见random()。
javascript
// 传入值:直接返回结果
gsap.utils.clamp(0, 100, 150); // 100
// 省略值:返回一个可后续调用的函数
let c = gsap.utils.clamp(0, 100);
c(150); // 100
c(-10); // 0Clamping and Ranges
数值限制与范围处理
clamp(min, max, value?)
clamp(min, max, value?)
Constrains a value between min and max. Omit value to get a function: .
clamp(min, max)(value)javascript
gsap.utils.clamp(0, 100, 150); // 100
gsap.utils.clamp(0, 100, -10); // 0
let clampFn = gsap.utils.clamp(0, 100);
clampFn(150); // 100将值限制在min和max之间。省略value可获取函数形式:。
clamp(min, max)(value)javascript
gsap.utils.clamp(0, 100, 150); // 100
gsap.utils.clamp(0, 100, -10); // 0
let clampFn = gsap.utils.clamp(0, 100);
clampFn(150); // 100mapRange(inMin, inMax, outMin, outMax, value?)
mapRange(inMin, inMax, outMin, outMax, value?)
Maps a value from one range to another. Use when converting scroll position, progress (0–1), or input range to an animation range. Omit value to get a function: .
mapRange(inMin, inMax, outMin, outMax)(value)javascript
gsap.utils.mapRange(0, 100, 0, 500, 50); // 250
gsap.utils.mapRange(0, 1, 0, 360, 0.5); // 180 (progress to degrees)
let mapFn = gsap.utils.mapRange(0, 100, 0, 500);
mapFn(50); // 250将值从一个范围映射到另一个范围。适用于将滚动位置、进度(0–1)或输入范围转换为动画范围。省略value可获取函数形式:。
mapRange(inMin, inMax, outMin, outMax)(value)javascript
gsap.utils.mapRange(0, 100, 0, 500, 50); // 250
gsap.utils.mapRange(0, 1, 0, 360, 0.5); // 180(进度转角度)
let mapFn = gsap.utils.mapRange(0, 100, 0, 500);
mapFn(50); // 250normalize(min, max, value?)
normalize(min, max, value?)
Returns a value normalized to 0–1 for the given range. Inverse of mapping when the target range is 0–1. Omit value to get a function: .
normalize(min, max)(value)javascript
gsap.utils.normalize(0, 100, 50); // 0.5
gsap.utils.normalize(100, 300, 200); // 0.5
let normFn = gsap.utils.normalize(0, 100);
normFn(50); // 0.5将给定范围内的值归一化到0–1区间。当目标范围为0–1时,是映射操作的逆过程。省略value可获取函数形式:。
normalize(min, max)(value)javascript
gsap.utils.normalize(0, 100, 50); // 0.5
gsap.utils.normalize(100, 300, 200); // 0.5
let normFn = gsap.utils.normalize(0, 100);
normFn(50); // 0.5interpolate(start, end, progress?)
interpolate(start, end, progress?)
Interpolates between two values at a given progress (0–1). Handles numbers, colors, and objects with matching keys. Omit progress to get a function: .
interpolate(start, end)(progress)javascript
gsap.utils.interpolate(0, 100, 0.5); // 50
gsap.utils.interpolate("#ff0000", "#0000ff", 0.5); // mid color
gsap.utils.interpolate({ x: 0, y: 0 }, { x: 100, y: 50 }, 0.5); // { x: 50, y: 25 }
let lerp = gsap.utils.interpolate(0, 100);
lerp(0.5); // 50在给定进度(0–1)下,在两个值之间进行插值计算。支持数字、颜色以及具有匹配键的对象。省略progress可获取函数形式:。
interpolate(start, end)(progress)javascript
gsap.utils.interpolate(0, 100, 0.5); // 50
gsap.utils.interpolate("#ff0000", "#0000ff", 0.5); // 中间色
gsap.utils.interpolate({ x: 0, y: 0 }, { x: 100, y: 50 }, 0.5); // { x: 50, y: 25 }
let lerp = gsap.utils.interpolate(0, 100);
lerp(0.5); // 50Random and Snap
随机数与对齐
random(minimum, maximum[, snapIncrement, returnFunction]) / random(array[, returnFunction])
random(minimum, maximum[, snapIncrement, returnFunction]) / random(array[, returnFunction])
Returns a random number in the range minimum–maximum, or a random element from an array. Optional snapIncrement snaps the result to the nearest multiple (e.g. → multiples of 5). To get a reusable function, pass true as the last argument (returnFunction); the returned function takes no args and returns a new random value each time. This is the only util that uses for the function form instead of omitting the value.
5truejavascript
// immediate value: number in range
gsap.utils.random(-100, 100); // e.g. 42.7
gsap.utils.random(0, 500, 5); // 0–500, snapped to nearest 5
// reusable function: pass true as last argument
let randomFn = gsap.utils.random(-200, 500, 10, true);
randomFn(); // random value in range, snapped to 10
randomFn(); // another random value
// array: pick one value at random
gsap.utils.random(["red", "blue", "green"]); // "red", "blue", or "green"
let randomFromArray = gsap.utils.random([0, 100, 200], true);
randomFromArray(); // 0, 100, or 200String form in tween vars: use , , or ; GSAP evaluates it per target.
"random(-100, 100)""random(-100, 100, 5)""random([0, 100, 200])"javascript
gsap.to(".box", { x: "random(-100, 100, 5)", duration: 1 });
gsap.to(".item", { backgroundColor: "random([red, blue, green])" });返回minimum–maximum范围内的随机数,或从array中随机选取一个元素。可选参数snapIncrement可将结果对齐到最近的倍数(例如 → 5的倍数)。要获取可复用函数,需传入true作为最后一个参数(returnFunction);返回的函数无需传参,每次调用都会返回新的随机值。这是唯一一个使用来获取函数形式而非省略值的工具函数。
5truejavascript
// 直接获取值:范围内的随机数
gsap.utils.random(-100, 100); // 例如 42.7
gsap.utils.random(0, 500, 5); // 0–500之间,对齐到最近的5的倍数
// 可复用函数:传入true作为最后一个参数
let randomFn = gsap.utils.random(-200, 500, 10, true);
randomFn(); // 范围内的随机值,对齐到10的倍数
randomFn(); // 另一个随机值
// 数组:随机选取一个元素
gsap.utils.random(["red", "blue", "green"]); // "red"、"blue"或"green"
let randomFromArray = gsap.utils.random([0, 100, 200], true);
randomFromArray(); // 0、100或200补间变量中的字符串形式: 使用、或;GSAP会为每个目标单独计算。
"random(-100, 100)""random(-100, 100, 5)""random([0, 100, 200])"javascript
gsap.to(".box", { x: "random(-100, 100, 5)", duration: 1 });
gsap.to(".item", { backgroundColor: "random([red, blue, green])" });snap(snapTo, value?)
snap(snapTo, value?)
Snaps a value to the nearest multiple of snapTo, or to the nearest value in an array of allowed values. Omit value to get a function: (or ).
snap(snapTo)(value)snap(snapArray)(value)javascript
gsap.utils.snap(10, 23); // 20
gsap.utils.snap(0.25, 0.7); // 0.75
gsap.utils.snap([0, 100, 200], 150); // 100 or 200 (nearest in array)
let snapFn = gsap.utils.snap(10);
snapFn(23); // 20Use in tweens for grid or step-based animation:
javascript
gsap.to(".x", { x: 200, snap: { x: 20 } });将值对齐到snapTo的最近倍数,或对齐到允许值数组中的最近值。省略value可获取函数形式:(或)。
snap(snapTo)(value)snap(snapArray)(value)javascript
gsap.utils.snap(10, 23); // 20
gsap.utils.snap(0.25, 0.7); // 0.75
gsap.utils.snap([0, 100, 200], 150); // 100或200(数组中最近的值)
let snapFn = gsap.utils.snap(10);
snapFn(23); // 20在补间中用于网格或基于步骤的动画:
javascript
gsap.to(".x", { x: 200, snap: { x: 20 } });shuffle(array)
shuffle(array)
Returns a new array with the same elements in random order. Use for randomizing order (e.g. stagger from "random" with a copy).
javascript
gsap.utils.shuffle([1, 2, 3, 4]); // e.g. [3, 1, 4, 2]返回一个元素顺序随机打乱的新数组。用于随机化顺序(例如配合“random” stagger效果使用副本)。
javascript
gsap.utils.shuffle([1, 2, 3, 4]); // 例如 [3, 1, 4, 2]distribute(config)
distribute(config)
Returns a function that assigns a value to each target based on its position in the array (or in a grid). Used internally for advanced staggers; use it whenever you need values spread across many elements (e.g. scale, opacity, x, delay). The returned function receives — either call it manually or pass the result directly into a tween; GSAP will call it per target with index, element, and array.
(index, target, targets)Config (all optional):
| Property | Type | Description |
|---|---|---|
| Number | Starting value. Default |
| Number | Total to distribute across all targets (added to base). E.g. |
| Number | Amount to add between each target (added to base). E.g. |
| Number | String | Array | Where distribution starts: index, or |
| String | Array | Use grid position instead of flat index: |
| String | For grid: limit to one axis ( |
| Ease | Distribute values along an ease curve (e.g. |
In a tween: pass the result of as the property value; GSAP calls the function for each target with .
distribute(config)(index, target, targets)javascript
// Scale: middle elements 0.5, outer edges 3 (amount 2.5 distributed from center)
gsap.to(".class", {
scale: gsap.utils.distribute({
base: 0.5,
amount: 2.5,
from: "center"
})
});Manual use: call the returned function with to get the value for that index.
(index, target, targets)javascript
const distributor = gsap.utils.distribute({
base: 50,
amount: 100,
from: "center",
ease: "power1.inOut"
});
const targets = gsap.utils.toArray(".box");
const valueForIndex2 = distributor(2, targets[2], targets);See distribute() for more.
返回一个函数,该函数会根据目标在数组(或网格)中的位置为每个目标分配值。内部用于高级 stagger 效果;当你需要为多个元素分配值(例如缩放、透明度、x轴偏移、延迟时间)时可使用。返回的函数接收参数 —— 你可以手动调用它,也可直接将结果传入补间;GSAP会为每个目标传入索引、元素和数组进行调用。
(index, target, targets)配置参数(均为可选):
| 属性 | 类型 | 描述 |
|---|---|---|
| 数字 | 起始值。默认值 |
| 数字 | 要分配给所有目标的总值(会添加到base上)。例如 |
| 数字 | 每个目标之间要添加的量(会添加到base上)。例如 |
| 数字 | 字符串 | 数组 | 分配的起始位置:索引,或 |
| 字符串 | 数组 | 使用网格位置而非扁平索引: |
| 字符串 | 针对网格:限制为单个轴( |
| 缓动函数 | 沿缓动曲线分配值(例如 |
在补间中使用: 将的结果作为属性值传入;GSAP会为每个目标调用该函数并传入。
distribute(config)(index, target, targets)javascript
// 缩放:中间元素为0.5,边缘元素为3(从中心分配总量2.5)
gsap.to(".class", {
scale: gsap.utils.distribute({
base: 0.5,
amount: 2.5,
from: "center"
})
});手动使用: 调用返回的函数并传入来获取对应索引的值。
(index, target, targets)javascript
const distributor = gsap.utils.distribute({
base: 50,
amount: 100,
from: "center",
ease: "power1.inOut"
});
const targets = gsap.utils.toArray(".box");
const valueForIndex2 = distributor(2, targets[2], targets);更多详情请见distribute()。
Units and Parsing
单位与解析
getUnit(value)
getUnit(value)
Returns the unit string of a value (e.g. , , ). Use when normalizing or converting values.
"px""%""deg"javascript
gsap.utils.getUnit("100px"); // "px"
gsap.utils.getUnit("50%"); // "%"
gsap.utils.getUnit(42); // "" (unitless)返回值的单位字符串(例如、、)。在归一化或转换值时使用。
"px""%""deg"javascript
gsap.utils.getUnit("100px"); // "px"
gsap.utils.getUnit("50%"); // "%"
gsap.utils.getUnit(42); // ""(无单位)unitize(value, unit)
unitize(value, unit)
Appends a unit to a number, or returns the value as-is if it already has a unit. Use when building CSS values or tween end values.
javascript
gsap.utils.unitize(100, "px"); // "100px"
gsap.utils.unitize("2rem", "px"); // "2rem" (unchanged)为数字添加单位,若值已包含单位则直接返回原值。在构建CSS值或补间结束值时使用。
javascript
gsap.utils.unitize(100, "px"); // "100px"
gsap.utils.unitize("2rem", "px"); // "2rem"(保持不变)splitColor(color, returnHSL?)
splitColor(color, returnHSL?)
Converts a color string into an array: [red, green, blue] (0–255), or [red, green, blue, alpha] (4 elements for RGBA when alpha is present or required). Pass true as the second argument (returnHSL) to get [hue, saturation, lightness] or [hue, saturation, lightness, alpha] (HSL/HSLA) instead. Works with , , , , hex, and named colors (e.g. ). Use when animating color components or building gradients. See splitColor().
"rgb()""rgba()""hsl()""hsla()""red"javascript
gsap.utils.splitColor("red"); // [255, 0, 0]
gsap.utils.splitColor("#6fb936"); // [111, 185, 54]
gsap.utils.splitColor("rgba(204, 153, 51, 0.5)"); // [204, 153, 51, 0.5] (4 elements)
gsap.utils.splitColor("#6fb936", true); // [94, 55, 47] (HSL: hue, saturation, lightness)将颜色字符串转换为数组:[红色, 绿色, 蓝色](0–255),或当存在alpha通道或需要时返回**[红色, 绿色, 蓝色, alpha](4个元素)。传入true作为第二个参数(returnHSL)可获取[色相, 饱和度, 亮度]或[色相, 饱和度, 亮度, alpha]**(HSL/HSLA)格式。支持、、、、十六进制颜色和命名颜色(例如)。在为颜色分量设置动画或创建渐变时使用。详情请见splitColor()。
"rgb()""rgba()""hsl()""hsla()""red"javascript
gsap.utils.splitColor("red"); // [255, 0, 0]
gsap.utils.splitColor("#6fb936"); // [111, 185, 54]
gsap.utils.splitColor("rgba(204, 153, 51, 0.5)"); // [204, 153, 51, 0.5](4个元素)
gsap.utils.splitColor("#6fb936", true); // [94, 55, 47](HSL:色相、饱和度、亮度)Arrays and Collections
数组与集合
selector(scope)
selector(scope)
Returns a scoped selector function that finds elements only within the given element (or ref). Use in components so selectors like match only descendants of that component, not the whole document. Accepts a DOM element or a ref (e.g. React ref; handles ).
".box".currentjavascript
const q = gsap.utils.selector(containerRef);
q(".box"); // array of .box elements inside container
gsap.to(q(".circle"), { x: 100 });返回一个作用域选择器函数,该函数仅在给定元素(或ref)内部查找元素。在组件中使用,可让这类选择器仅匹配该组件的后代元素,而非整个文档。支持DOM元素或ref(例如React ref;会处理属性)。
.box.currentjavascript
const q = gsap.utils.selector(containerRef);
q(".box"); // container内部的.box元素数组
gsap.to(q(".circle"), { x: 100 });toArray(value, scope?)
toArray(value, scope?)
Converts a value to an array: selector string (scoped to element), NodeList, HTMLCollection, single element, or array. Use when passing mixed inputs to GSAP (e.g. targets) and a true array is needed.
javascript
gsap.utils.toArray(".item"); // array of elements
gsap.utils.toArray(".item", container); // scoped to container
gsap.utils.toArray(nodeList); // [ ... ] from NodeList将值转换为数组:支持选择器字符串(作用域限定到元素)、NodeList、HTMLCollection、单个元素或数组。当GSAP或你的代码需要从选择器或NodeList获取真实数组时使用。
javascript
gsap.utils.toArray(".item"); // 元素数组
gsap.utils.toArray(".item", container); // 作用域限定到container
gsap.utils.toArray(nodeList); // 从NodeList转换为数组pipe(...functions)
pipe(...functions)
Composes functions: pipe(f1, f2, f3)(value) returns f3(f2(f1(value))). Use when applying a chain of transforms (e.g. normalize → mapRange → snap) in a tween or callback.
javascript
const fn = gsap.utils.pipe(
(v) => gsap.utils.normalize(0, 100, v),
(v) => gsap.utils.snap(0.1, v)
);
fn(50); // normalized then snapped组合多个函数:pipe(f1, f2, f3)(value) 返回f3(f2(f1(value)))。在补间或回调中应用一系列转换(例如归一化→映射范围→对齐)时使用。
javascript
const fn = gsap.utils.pipe(
(v) => gsap.utils.normalize(0, 100, v),
(v) => gsap.utils.snap(0.1, v)
);
fn(50); // 先归一化再对齐wrap(min, max, value?)
wrap(min, max, value?)
Wraps a value into the range min–max (inclusive min, exclusive max). Use for infinite scroll or cyclic values. Omit value to get a function: .
wrap(min, max)(value)javascript
gsap.utils.wrap(0, 360, 370); // 10
gsap.utils.wrap(0, 360, -10); // 350
let wrapFn = gsap.utils.wrap(0, 360);
wrapFn(370); // 10将值包裹到min–max范围内(包含min,不包含max)。用于无限滚动或循环值。省略value可获取函数形式:。
wrap(min, max)(value)javascript
gsap.utils.wrap(0, 360, 370); // 10
gsap.utils.wrap(0, 360, -10); // 350
let wrapFn = gsap.utils.wrap(0, 360);
wrapFn(370); // 10wrapYoyo(min, max, value?)
wrapYoyo(min, max, value?)
Wraps value in range with a yoyo (bounces at ends). Use for back-and-forth within a range. Omit value to get a function: .
wrapYoyo(min, max)(value)javascript
gsap.utils.wrapYoyo(0, 100, 150); // 50 (bounces back)
let wrapY = gsap.utils.wrapYoyo(0, 100);
wrapY(150); // 50将值包裹到范围内并以往返形式呈现(在边界处反弹)。用于在范围内来回切换的值。省略value可获取函数形式:。
wrapYoyo(min, max)(value)javascript
gsap.utils.wrapYoyo(0, 100, 150); // 50(反弹回来)
let wrapY = gsap.utils.wrapYoyo(0, 100);
wrapY(150); // 50Best practices
最佳实践
- ✅ Omit the value argument to get a reusable function when the same range/config is used many times (e.g. scroll handler, tween callback): .
let mapFn = gsap.utils.mapRange(0, 1, 0, 360); mapFn(progress) - ✅ Use snap for grid-aligned or step-based values; use toArray when GSAP or your code needs a real array from a selector or NodeList.
- ✅ Use gsap.utils.selector(scope) in components so selectors are scoped to a container or ref.
- ✅ 当多次使用相同范围/配置时,省略值参数以获取可复用函数(例如滚动处理器、补间回调):。
let mapFn = gsap.utils.mapRange(0, 1, 0, 360); mapFn(progress) - ✅ 使用snap处理网格对齐或基于步骤的值;当GSAP或你的代码需要从选择器或NodeList获取真实数组时,使用toArray。
- ✅ 在组件中使用gsap.utils.selector(scope),让选择器作用域限定到容器或ref。
Do Not
注意事项
- ❌ Assume mapRange / normalize handle units; they work on numbers. Use getUnit / unitize when units matter.
- ❌ Override or rely on undocumented behavior; stick to the documented API.
- ❌ 不要假设mapRange / normalize会处理单位;它们仅对数字生效。当涉及单位时,请使用getUnit / unitize。
- ❌ 不要覆盖或依赖未记录的行为;请严格遵循已文档化的API。