import gsap from "gsap";
import { SplitText } from "gsap/SplitText";
gsap.registerPlugin(SplitText);
let split, currentAnimation;
const animations = {
chars: () => gsap.fromTo(split.chars,
{ x: 150, opacity: 0 },
{ x: 0, opacity: 1, duration: 0.7, ease: "power4", stagger: 0.04 }
),
words: () => gsap.fromTo(split.words,
{ y: -100, opacity: 0, rotation: "random(-80, 80)" },
{ y: 0, opacity: 1, rotation: 0, duration: 0.7, ease: "back", stagger: 0.15 }
),
lines: () => gsap.fromTo(split.lines,
{ rotationX: -100, opacity: 0 },
{ rotationX: 0, opacity: 1, duration: 0.8, ease: "power3", stagger: 0.25, transformOrigin: "50% 50% -160px" }
)
};
function resetText() {
gsap.set(split.chars, { x: 0, opacity: 1 });
gsap.set(split.words, { y: 0, opacity: 1, rotation: 0 });
gsap.set(split.lines, { rotationX: 0, opacity: 1 });
}
function playAnimation(animationFn) {
if (currentAnimation) {
currentAnimation.kill();
}
resetText();
return animationFn();
}
let currentIndex = 0;
function runNextAnimation() {
const keys = Object.keys(animations);
const nextKey = keys[currentIndex];
currentAnimation = playAnimation(animations[nextKey]);
currentAnimation.then(() => {
currentIndex = (currentIndex + 1) % keys.length;
setTimeout(runNextAnimation, 1000);
});
}
function setup() {
if (split) {
split.revert();
}
if (currentAnimation) {
currentAnimation.kill();
}
split = new SplitText(".text", { type: "chars,words,lines" });
}
// 点击事件
document.querySelector("#chars").addEventListener("click", () => {
currentAnimation = playAnimation(animations.chars);
});
document.querySelector("#words").addEventListener("click", () => {
currentAnimation = playAnimation(animations.words);
});
document.querySelector("#lines").addEventListener("click", () => {
currentAnimation = playAnimation(animations.lines);
});
// 初始化
setup();
runNextAnimation();
window.addEventListener("resize", setup);