gsap-自定义动画

72 阅读1分钟


  // 注册CustomEase插件
        gsap.registerPlugin(CustomEase);

        // 创建自定义缓动效果
        CustomEase.create("customBounce", "M0,0 C0.14,0 0.27,0.3 0.3,0.5 0.35,0.8 0.4,1 0.5,1 0.6,1 0.7,0.85 0.8,0.7 0.9,0.5 1,0");
        // 使用贝塞尔曲线定义弹跳效果

        // 弹跳动画
        function playBounce() {
            gsap.to(".bounce-box", {
                duration: 2,          // 动画持续时间2秒
                x: 200,              // X轴移动200像素
                ease: "customBounce", // 使用自定义弹跳缓动效果
                yoyo: true,          // 动画往返播放
                repeat: 1            // 重复1次(共播放2次)
            });
        }

        // 摆动动画
        function playSwing() {
            gsap.to(".swing-box", {
                duration: 2,          // 动画持续时间2秒
                rotation: 360,        // 旋转360度
                transformOrigin: "50% 200px", // 设置旋转中心点
                ease: "customSwing",  // 使用自定义摆动缓动效果
                yoyo: true,          // 动画往返播放
                repeat: 1            // 重复1次(共播放2次)
            });
        }

        // 弹性动画
        function playElastic() {
            gsap.to(".elastic-box", {
                duration: 2,          // 动画持续时间2秒
                scale: 2,            // 放大到2倍
                x: 200,              // X轴移动200像素
                ease: "customElastic", // 使用自定义弹性缓动效果
                yoyo: true,          // 动画往返播放
                repeat: 1            // 重复1次(共播放2次)
            });
        }

        // 自定义路径动画
        function playCustomPath() {
            gsap.to(".slider", {
                duration: 3,          // 动画持续时间3秒
                left: "100%",         // 移动到容器右侧
                ease: CustomEase.create("custom", "M0,0 C0.126,0.382 0.282,0.674 0.44,0.822 0.632,1.002 0.818,1.001 1,1"), // 自定义路径缓动
                yoyo: true,          // 动画往返播放
                repeat: 1            // 重复1次(共播放2次)
            });
        }

        // 悬停效果
        document.querySelectorAll('.box').forEach(box => {
            box.addEventListener('mouseenter', () => {
                gsap.to(box, {
                    duration: 0.3,           // 动画持续时间0.3秒
                    scale: 1.2,             // 放大到1.2倍
                    backgroundColor: "#e74c3c", // 改变背景色为红色
                    ease: "power2.out"      // 缓动效果:平滑减速
                });
            });

            box.addEventListener('mouseleave', () => {
                gsap.to(box, {
                    duration: 0.3,
                    scale: 1,
                    backgroundColor: "#3498db",
                    ease: "power2.in"
                });
            });
        });