gsap

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GSAP Animation Guidelines

GSAP 动画指南

You are an expert in GSAP (GreenSock Animation Platform), JavaScript, and web animation performance. Follow these guidelines when creating animations.
您是GSAP(GreenSock动画平台)、JavaScript和Web动画性能方面的专家。创建动画时请遵循以下指南。

Core Principles

核心原则

Import and Setup

导入与设置

javascript
// Modern ES Module import
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";

// Register plugins
gsap.registerPlugin(ScrollTrigger);
javascript
// Modern ES Module import
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";

// Register plugins
gsap.registerPlugin(ScrollTrigger);

Use gsap.to(), gsap.from(), and gsap.fromTo()

使用 gsap.to()、gsap.from() 和 gsap.fromTo()

javascript
// Animate TO a state
gsap.to(".element", { x: 100, duration: 1 });

// Animate FROM a state
gsap.from(".element", { opacity: 0, y: 50, duration: 0.5 });

// Animate FROM one state TO another
gsap.fromTo(".element",
  { opacity: 0 },
  { opacity: 1, duration: 0.5 }
);
javascript
// Animate TO a state
gsap.to(".element", { x: 100, duration: 1 });

// Animate FROM a state
gsap.from(".element", { opacity: 0, y: 50, duration: 0.5 });

// Animate FROM one state TO another
gsap.fromTo(".element",
  { opacity: 0 },
  { opacity: 1, duration: 0.5 }
);

Performance Optimization

性能优化

Leverage Hardware Acceleration

利用硬件加速

javascript
// Use transforms instead of positional properties
gsap.to(".element", {
  x: 100,      // Good - uses transform
  y: 50,       // Good - uses transform
  rotation: 45, // Good - uses transform
  scale: 1.2,  // Good - uses transform
  // Avoid: left, top, width, height when possible
});

// Enable force3D for GPU acceleration
gsap.to(".element", {
  x: 100,
  force3D: true // Ensures GPU acceleration
});
javascript
// Use transforms instead of positional properties
gsap.to(".element", {
  x: 100,      // Good - uses transform
  y: 50,       // Good - uses transform
  rotation: 45, // Good - uses transform
  scale: 1.2,  // Good - uses transform
  // Avoid: left, top, width, height when possible
});

// Enable force3D for GPU acceleration
gsap.to(".element", {
  x: 100,
  force3D: true // Ensures GPU acceleration
});

Use will-change Wisely

合理使用 will-change

javascript
// Apply will-change before animation
element.style.willChange = "transform";

gsap.to(element, {
  x: 100,
  onComplete: () => {
    element.style.willChange = "auto"; // Remove after animation
  }
});
javascript
// Apply will-change before animation
element.style.willChange = "transform";

gsap.to(element, {
  x: 100,
  onComplete: () => {
    element.style.willChange = "auto"; // Remove after animation
  }
});

Stagger for Multiple Elements

多元素动画使用 stagger

javascript
// Always use stagger for multiple elements
gsap.to(".items", {
  opacity: 1,
  y: 0,
  stagger: 0.1, // Prevents all elements animating at once
  duration: 0.5
});

// Advanced stagger options
gsap.to(".grid-items", {
  scale: 1,
  stagger: {
    each: 0.1,
    from: "center",
    grid: "auto"
  }
});
javascript
// Always use stagger for multiple elements
gsap.to(".items", {
  opacity: 1,
  y: 0,
  stagger: 0.1, // Prevents all elements animating at once
  duration: 0.5
});

// Advanced stagger options
gsap.to(".grid-items", {
  scale: 1,
  stagger: {
    each: 0.1,
    from: "center",
    grid: "auto"
  }
});

Use Lag Smoothing

使用延迟平滑

javascript
// Prevent animation stuttering during CPU spikes
gsap.ticker.lagSmoothing(1000, 16);
javascript
// Prevent animation stuttering during CPU spikes
gsap.ticker.lagSmoothing(1000, 16);

Timeline Best Practices

时间线最佳实践

Use Timelines for Complex Sequences

复杂序列使用时间线

javascript
const tl = gsap.timeline({
  defaults: { duration: 0.5, ease: "power2.out" }
});

tl.to(".header", { y: 0, opacity: 1 })
  .to(".content", { y: 0, opacity: 1 }, "-=0.3") // Overlap
  .to(".footer", { y: 0, opacity: 1 }, "-=0.3");
javascript
const tl = gsap.timeline({
  defaults: { duration: 0.5, ease: "power2.out" }
});

tl.to(".header", { y: 0, opacity: 1 })
  .to(".content", { y: 0, opacity: 1 }, "-=0.3") // Overlap
  .to(".footer", { y: 0, opacity: 1 }, "-=0.3");

Use Labels for Organization

使用标签进行组织

javascript
const tl = gsap.timeline();

tl.addLabel("start")
  .to(".intro", { opacity: 1 })
  .addLabel("middle")
  .to(".main", { x: 100 })
  .addLabel("end")
  .to(".outro", { opacity: 0 });

// Jump to label
tl.play("middle");
javascript
const tl = gsap.timeline();

tl.addLabel("start")
  .to(".intro", { opacity: 1 })
  .addLabel("middle")
  .to(".main", { x: 100 })
  .addLabel("end")
  .to(".outro", { opacity: 0 });

// Jump to label
tl.play("middle");

Control Timelines

控制时间线

javascript
const tl = gsap.timeline({ paused: true });

// Methods
tl.play();
tl.pause();
tl.reverse();
tl.restart();
tl.seek(1.5); // Go to 1.5 seconds
tl.progress(0.5); // Go to 50%
javascript
const tl = gsap.timeline({ paused: true });

// Methods
tl.play();
tl.pause();
tl.reverse();
tl.restart();
tl.seek(1.5); // Go to 1.5 seconds
tl.progress(0.5); // Go to 50%

ScrollTrigger Best Practices

ScrollTrigger 最佳实践

Basic ScrollTrigger Setup

基础 ScrollTrigger 设置

javascript
gsap.to(".element", {
  x: 500,
  scrollTrigger: {
    trigger: ".element",
    start: "top center",
    end: "bottom center",
    scrub: true,
    markers: false // Enable for debugging only
  }
});
javascript
gsap.to(".element", {
  x: 500,
  scrollTrigger: {
    trigger: ".element",
    start: "top center",
    end: "bottom center",
    scrub: true,
    markers: false // Enable for debugging only
  }
});

Pin Elements Properly

正确固定元素

javascript
ScrollTrigger.create({
  trigger: ".panel",
  pin: true,
  start: "top top",
  end: "+=500",
  pinSpacing: true
});
javascript
ScrollTrigger.create({
  trigger: ".panel",
  pin: true,
  start: "top top",
  end: "+=500",
  pinSpacing: true
});

Batch ScrollTriggers for Performance

批量处理 ScrollTrigger 以提升性能

javascript
ScrollTrigger.batch(".items", {
  onEnter: (elements) => {
    gsap.to(elements, {
      opacity: 1,
      y: 0,
      stagger: 0.1
    });
  }
});
javascript
ScrollTrigger.batch(".items", {
  onEnter: (elements) => {
    gsap.to(elements, {
      opacity: 1,
      y: 0,
      stagger: 0.1
    });
  }
});

React Integration

React 集成

Use useGSAP Hook

使用 useGSAP 钩子

javascript
import { useGSAP } from "@gsap/react";

function Component() {
  const containerRef = useRef(null);

  useGSAP(() => {
    gsap.to(".box", { x: 100 });
  }, { scope: containerRef }); // Scopes selectors to container

  return <div ref={containerRef}>...</div>;
}
javascript
import { useGSAP } from "@gsap/react";

function Component() {
  const containerRef = useRef(null);

  useGSAP(() => {
    gsap.to(".box", { x: 100 });
  }, { scope: containerRef }); // Scopes selectors to container

  return <div ref={containerRef}>...</div>;
}

Cleanup Animations

清理动画

javascript
useGSAP(() => {
  const tl = gsap.timeline();
  tl.to(".element", { x: 100 });

  return () => {
    tl.kill(); // Clean up on unmount
  };
}, []);
javascript
useGSAP(() => {
  const tl = gsap.timeline();
  tl.to(".element", { x: 100 });

  return () => {
    tl.kill(); // Clean up on unmount
  };
}, []);

Selector Optimization

选择器优化

Cache DOM Selectors

缓存DOM选择器

javascript
// Bad - queries DOM on every call
gsap.to(".element", { x: 100 });
gsap.to(".element", { y: 50 });

// Good - cache the reference
const element = document.querySelector(".element");
gsap.to(element, { x: 100 });
gsap.to(element, { y: 50 });
javascript
// Bad - queries DOM on every call
gsap.to(".element", { x: 100 });
gsap.to(".element", { y: 50 });

// Good - cache the reference
const element = document.querySelector(".element");
gsap.to(element, { x: 100 });
gsap.to(element, { y: 50 });

Use gsap.utils for Efficiency

使用 gsap.utils 提升效率

javascript
// Convert NodeList to Array
const items = gsap.utils.toArray(".items");

// Create reusable selector
const select = gsap.utils.selector(container);
gsap.to(select(".box"), { x: 100 });
javascript
// Convert NodeList to Array
const items = gsap.utils.toArray(".items");

// Create reusable selector
const select = gsap.utils.selector(container);
gsap.to(select(".box"), { x: 100 });

Easing

缓动效果

Use Appropriate Eases

使用合适的缓动函数

javascript
// Common eases for UI
gsap.to(".element", { x: 100, ease: "power2.out" }); // Decelerate
gsap.to(".element", { x: 100, ease: "power2.in" });  // Accelerate
gsap.to(".element", { x: 100, ease: "power2.inOut" }); // Both

// Bounce and elastic for playful UI
gsap.to(".element", { y: 0, ease: "bounce.out" });
gsap.to(".element", { scale: 1, ease: "elastic.out(1, 0.3)" });
javascript
// Common eases for UI
gsap.to(".element", { x: 100, ease: "power2.out" }); // Decelerate
gsap.to(".element", { x: 100, ease: "power2.in" });  // Accelerate
gsap.to(".element", { x: 100, ease: "power2.inOut" }); // Both

// Bounce and elastic for playful UI
gsap.to(".element", { y: 0, ease: "bounce.out" });
gsap.to(".element", { scale: 1, ease: "elastic.out(1, 0.3)" });

SVG Animation

SVG 动画

Animate SVG Properties

动画SVG属性

javascript
gsap.to("path", {
  strokeDashoffset: 0,
  duration: 2,
  ease: "none"
});

gsap.to("circle", {
  attr: { r: 50, cx: 200 },
  duration: 1
});
javascript
gsap.to("path", {
  strokeDashoffset: 0,
  duration: 2,
  ease: "none"
});

gsap.to("circle", {
  attr: { r: 50, cx: 200 },
  duration: 1
});

Complex Animations

复杂动画

Use MotionPath for Path Animation

使用 MotionPath 实现路径动画

javascript
import { MotionPathPlugin } from "gsap/MotionPathPlugin";
gsap.registerPlugin(MotionPathPlugin);

gsap.to(".element", {
  motionPath: {
    path: "#path",
    align: "#path",
    autoRotate: true
  },
  duration: 5
});
javascript
import { MotionPathPlugin } from "gsap/MotionPathPlugin";
gsap.registerPlugin(MotionPathPlugin);

gsap.to(".element", {
  motionPath: {
    path: "#path",
    align: "#path",
    autoRotate: true
  },
  duration: 5
});

Debugging

调试

Use Markers During Development

开发期间使用标记

javascript
ScrollTrigger.defaults({
  markers: process.env.NODE_ENV === "development"
});
javascript
ScrollTrigger.defaults({
  markers: process.env.NODE_ENV === "development"
});

Debug Timeline Progress

调试时间线进度

javascript
tl.eventCallback("onUpdate", () => {
  console.log(tl.progress());
});
javascript
tl.eventCallback("onUpdate", () => {
  console.log(tl.progress());
});

Best Practices Summary

最佳实践总结

  1. Always use transforms over positional properties
  2. Use stagger for animating multiple elements
  3. Leverage timelines for complex sequences
  4. Cache DOM selectors
  5. Use useGSAP hook in React
  6. Clean up animations on component unmount
  7. Enable lag smoothing for smooth playback
  8. Test on actual devices, especially mobile
  1. 始终优先使用transform而非位置属性
  2. 多元素动画时使用stagger
  3. 复杂动画序列使用时间线
  4. 缓存DOM选择器
  5. 在React中使用useGSAP钩子
  6. 组件卸载时清理动画
  7. 启用延迟平滑以实现流畅播放
  8. 在真实设备上测试,尤其是移动设备