Communitygithub.com

ComeOnOliver/skillshub

Mejores prácticas de animación GSAP para diseño web: disparadores de scroll, optimización de rendimiento, accesibilidad, animaciones responsivas e integración de pruebas. Úsalo al implementar o revisar animaciones en WordPress o cualquier proyecto web.

¿Qué es skillshub?

Esta habilidad proporciona una guía completa y detallada sobre las mejores prácticas para implementar animaciones profesionales, accesibles y de alto rendimiento utilizando GSAP (GreenSock Animation Platform). Es útil para cualquier desarrollador o diseñador web que trabaje en proyectos de WordPress u otros sitios web, ya que cubre desde la configuración inicial con CDN o WordPress Enqueue hasta patrones de animación comunes como fundidos, parallax, y revelaciones de texto. La guía enfatiza la importancia de la accesibilidad (respetando `prefers-reduced-motion` y asegurando que el contenido sea visible sin JavaScript), el rendimiento (animando solo propiedades GPU-aceleradas como `transform` y `opacity`), y la mejora progresiva (las animaciones mejoran, no reemplazan, la funcionalidad). Incluye una biblioteca de animaciones reutilizable, guías para pruebas de integración con Visual QA y Playwright, y una lista de verificación previa al lanzamiento para garantizar animaciones optimizadas y accesibles en todos los dispositivos.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/crazyswami/gsap-animations

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Vista previa

Del README del skill

skillshub preview

Documentación

Mejores Prácticas de Animación GSAP

Guía completa para implementar animaciones profesionales, accesibles y de alto rendimiento usando GSAP (GreenSock Animation Platform).

Principios Fundamentales

1. Rendimiento Primero

  • Animar solo transform y opacity (acelerados por GPU)
  • Evitar animar width, height, top, left, margin, padding
  • Usar will-change con moderación
  • Apuntar a 60fps en todos los dispositivos

2. Accesibilidad Siempre

  • Respetar prefers-reduced-motion
  • Asegurar que el contenido sea visible sin JavaScript
  • No ocultar contenido crítico detrás de animaciones
  • Proporcionar controles de salto/pausa para animaciones largas

3. Mejora Progresiva

  • El contenido debe funcionar sin animaciones
  • Las animaciones mejoran, no reemplazan, la funcionalidad
  • Probar con animaciones deshabilitadas

Configuración de GSAP

Instalación

<!-- CDN (recomendado para WordPress) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>

<!-- Plugins opcionales -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollSmoother.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/SplitText.min.js"></script>

WordPress Enqueue

function theme_enqueue_gsap() {
    // Núcleo de GSAP
    wp_enqueue_script(
        'gsap',
        'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js',
        array(),
        '3.12.5',
        true
    );

    // ScrollTrigger
    wp_enqueue_script(
        'gsap-scrolltrigger',
        'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js',
        array('gsap'),
        '3.12.5',
        true
    );

    // Animaciones del tema
    wp_enqueue_script(
        'theme-animations',
        get_theme_file_uri('/assets/js/animations.js'),
        array('gsap', 'gsap-scrolltrigger'),
        filemtime(get_theme_file_path('/assets/js/animations.js')),
        true
    );
}
add_action('wp_enqueue_scripts', 'theme_enqueue_gsap');

Patrones de Animación

1. Fundido al Hacer Scroll

// Fundido básico
gsap.from('.fade-in', {
    opacity: 0,
    y: 50,
    duration: 1,
    stagger: 0.2,
    scrollTrigger: {
        trigger: '.fade-in',
        start: 'top 80%',
        toggleActions: 'play none none none'
    }
});

2. Elementos Escalonados

// Tarjetas apareciendo una por una
gsap.from('.card', {
    opacity: 0,
    y: 100,
    duration: 0.8,
    stagger: {
        amount: 0.6,
        from: 'start'
    },
    ease: 'power2.out',
    scrollTrigger: {
        trigger: '.cards-container',
        start: 'top 75%'
    }
});

3. Efecto Parallax

// Parallax sutil en imágenes
gsap.to('.parallax-image', {
    yPercent: -20,
    ease: 'none',
    scrollTrigger: {
        trigger: '.parallax-section',
        start: 'top bottom',
        end: 'bottom top',
        scrub: true
    }
});

4. Revelación de Texto (Línea por Línea)

// Requiere el plugin SplitText (Club GreenSock)
// O usar la alternativa CSS a continuación

// Alternativa CSS - envolver cada línea en un span
gsap.from('.reveal-line', {
    opacity: 0,
    y: '100%',
    duration: 0.8,
    stagger: 0.1,
    ease: 'power3.out',
    scrollTrigger: {
        trigger: '.text-reveal',
        start: 'top 80%'
    }
});

5. Revelación con Cortina/Máscara

// Imagen revelada por una máscara deslizante
gsap.to('.curtain-mask', {
    scaleX: 0,
    transformOrigin: 'right center',
    duration: 1.2,
    ease: 'power4.inOut',
    scrollTrigger: {
        trigger: '.curtain-container',
        start: 'top 70%'
    }
});

6. Línea de Tiempo de Héroe

// Secuencia compleja de héroe
const heroTL = gsap.timeline({
    defaults: { ease: 'power3.out' }
});

heroTL
    .from('.hero-bg', { scale: 1.2, duration: 1.5 })
    .from('.hero-title', { opacity: 0, y: 100, duration: 1 }, '-=1')
    .from('.hero-subtitle', { opacity: 0, y: 50, duration: 0.8 }, '-=0.5')
    .from('.hero-cta', { opacity: 0, y: 30, duration: 0.6 }, '-=0.3');

Accesibilidad

Respetar Movimiento Reducido

// Verificar preferencia del usuario
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

// Opción 1: Deshabilitar todas las animaciones
if (prefersReducedMotion) {
    gsap.globalTimeline.timeScale(0);
    ScrollTrigger.getAll().forEach(st => st.kill());
}

// Opción 2: Animaciones simplificadas
const animationConfig = prefersReducedMotion
    ? { duration: 0, stagger: 0 }
    : { duration: 1, stagger: 0.2 };

gsap.from('.element', {
    opacity: 0,
    y: prefersReducedMotion ? 0 : 50,
    ...animationConfig
});

Alternativa CSS

/* Asegurar que el contenido sea visible sin JS */
.fade-in {
    opacity: 1;
    transform: translateY(0);
}

/* Ocultar solo si las animaciones se ejecutarán */
.js .fade-in {
    opacity: 0;
    transform: translateY(50px);
}

/* Respetar movimiento reducido también en CSS */
@media (prefers-reduced-motion: reduce) {
    .js .fade-in {
        opacity: 1;
        transform: none;
    }
}

Agregar Clase JS al HTML

// Agregar al inicio del script
document.documentElement.classList.add('js');

Animaciones Responsivas

Animaciones Conscientes de Puntos de Corte

// Crear animaciones responsivas
const mm = gsap.matchMedia();

mm.add('(min-width: 1024px)', () => {
    // Animaciones de escritorio
    gsap.from('.hero-image', {
        x: 100,
        opacity: 0,
        duration: 1.2
    });

    return () => {
        // Limpiar al cambiar de punto de corte
    };
});

mm.add('(max-width: 1023px)', () => {
    // Animaciones móviles (más simples)
    gsap.from('.hero-image', {
        opacity: 0,
        duration: 0.8
    });
});

Actualizar al Redimensionar

// Recalcular ScrollTrigger al redimensionar
let resizeTimer;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        ScrollTrigger.refresh();
    }, 250);
});

Optimización de Rendimiento

1. Usar Solo Propiedades de Transformación

// BUENO - Acelerado por GPU
gsap.to('.element', {
    x: 100,          // transform: translateX
    y: 50,           // transform: translateY
    rotation: 45,    // transform: rotate
    scale: 1.2,      // transform: scale
    opacity: 0.5
});

// MALO - Provoca layout/paint
gsap.to('.element', {
    left: 100,       // Provoca layout
    width: '200px',  // Provoca layout
    marginTop: 50    // Provoca layout
});

2. Agrupar Animaciones Similares

// Usar batch para muchos elementos similares
ScrollTrigger.batch('.card', {
    onEnter: batch => gsap.to(batch, {
        opacity: 1,
        y: 0,
        stagger: 0.1
    }),
    start: 'top 85%'
});

3. Eliminar ScrollTriggers No Usados

// Limpiar al navegar (SPA) o desmontar componente
function cleanup() {
    ScrollTrigger.getAll().forEach(st => st.kill());
    gsap.killTweensOf('*');
}

4. Inicialización Perezosa

// Solo inicializar animaciones para secciones visibles
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            initSectionAnimations(entry.target);
            observer.unobserve(entry.target);
        }
    });
}, { rootMargin: '100px' });

document.querySelectorAll('.animated-section').forEach(section => {
    observer.observe(section);
});

Mejores Prácticas de ScrollTrigger

1. Puntos de Inicio/Fin Adecuados

// Evitar errores comunes
ScrollTrigger.create({
    trigger: '.section',
    start: 'top 80%',    // Cuando la parte superior del activador está al 80% desde la parte superior del viewport
    end: 'bottom 20%',   // Cuando la parte inferior del activador está al 20% desde la parte superior
    markers: true,       // Solo depuración - ¡eliminar en producción!
});

2. Fijar Secciones con Cuidado

// Fijar puede causar problemas de layout
ScrollTrigger.create({
    trigger: '.pinned-section',
    start: 'top top',
    end: '+=100%',
    pin: true,
    pinSpacing: true,    // Generalmente se quiere esto true
    anticipatePin: 1     // Ayuda en móvil
});

3. Manejar Carga de Imágenes

// Esperar a que las imágenes carguen antes de calcular posiciones
ScrollTrigger.config({
    ignoreMobileResize: true
});

window.addEventListener('load', () => {
    ScrollTrigger.refresh();
});

// O actualizar después de que las imágenes perezosas carguen
document.querySelectorAll('img[loading="lazy"]').forEach(img => {
    img.addEventListener('load', () => ScrollTrigger.refresh());
});

Integración de Pruebas

Compatibilidad con Visual QA

Para que la habilidad visual-qa capture las animaciones correctamente:

// Exponer función para completar todas las animaciones instantáneamente
window.completeAllAnimations = function() {
    gsap.globalTimeline.progress(1);
    ScrollTrigger.getAll().forEach(st => {
        st.scroll(st.end);
    });
};

// O saltar animaciones por completo para capturas de pantalla
if (window.location.search.includes('skip-animations')) {
    gsap.globalTimeline.timeScale(100);
}

Pruebas con Playwright

// En una prueba de Playwright
await page.evaluate(() => {
    if (window.completeAllAnimations) {
        window.completeAllAnimations();
    }
});
await page.waitForTimeout(500);
await page.screenshot({ path: 'screenshot.png', fullPage: true });

Biblioteca de Animaciones Común

Clases de Animación Reutilizables

// animations.js - Biblioteca de animaciones reutilizables

const Animations = {
    // Inicializar todas las animaciones
    init() {
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            return;
        }

        this.fadeIn();
        this.slideIn();
        this.parallax();
        this.textReveal();
    },

    fadeIn() {
        gsap.utils.toArray('[data-animate="fade-in"]').forEach(el => {
            gsap.from(el, {
                opacity: 0,
                y: 50,
                duration: 0.8,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 85%',
                    once: true
                }
            });
        });
    },

    slideIn() {
        gsap.utils.toArray('[data-animate="slide-left"]').forEach(el => {
            gsap.from(el, {
                opacity: 0,
                x: -100,
                duration: 1,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 80%',
                    once: true
                }
            });
        });

        gsap.utils.toArray('[data-animate="slide-right"]').forEach(el => {
            gsap.from(el, {
                opacity: 0,
                x: 100,
                duration: 1,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 80%',
                    once: true
                }
            });
        });
    },

    parallax() {
        gsap.utils.toArray('[data-parallax]').forEach(el => {
            const speed = el.dataset.parallax || 0.2;
            gsap.to(el, {
                yPercent: -100 * speed,
                ease: 'none',
                scrollTrigger: {
                    trigger: el.parentElement,
                    start: 'top bottom',
                    end: 'bottom top',
                    scrub: true
                }
            });
        });
    },

    textReveal() {
        gsap.utils.toArray('[data-animate="text-reveal"]').forEach(el => {
            const lines = el.querySelectorAll('.line');
            gsap.from(lines, {
                opacity: 0,
                y: '100%',
                duration: 0.8,
                stagger: 0.1,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 80%',
                    once: true
                }
            });
        });
    },

    // Actualizar después de contenido dinámico
    refresh() {
        ScrollTrigger.refresh();
    },

    // Limpiar para navegación SPA
    destroy() {
        ScrollTrigger.getAll().forEach(st => st.kill());
        gsap.killTweensOf('*');
    }
};

// Inicializar cuando el DOM esté listo
document.addEventListener('DOMContentLoaded', () => Animations.init());

Uso en HTML

<!-- Fundido -->
<div data-animate="fade-in">Contenido</div>

<!-- Deslizar desde la izquierda -->
<div data-animate="slide-left">Contenido</div>

<!-- Parallax (0.2 = 20% de velocidad) -->
<img data-parallax="0.3" src="image.jpg">

<!-- Revelación de texto (requiere envolver líneas) -->
<div data-animate="text-reveal">
    <div class="line">Primera línea</div>
    <div class="line">Segunda línea</div>
</div>

Depuración

Habilitar Marcadores

ScrollTrigger.defaults({
    markers: true  // Muestra marcadores de inicio/fin
});

Registrar Eventos de Animación

gsap.to('.element', {
    x: 100,
    onStart: () => console.log('Animación iniciada'),
    onComplete: () => console.log('Animación completada'),
    onUpdate: self => console.log('Progreso:', self.progress())
});

Verificar Problemas

// Listar todos los ScrollTriggers
console.log('ScrollTriggers:', ScrollTrigger.getAll());

// Verificar si el elemento existe
const el = document.querySelector('.animated-element');
if (!el) console.warn('¡Destino de animación no encontrado!');

Lista de Verificación

Antes del Lanzamiento

  • Eliminar todos los markers: true
  • Probar con prefers-reduced-motion: reduce
  • Probar en dispositivos móviles (dispositivos reales, no solo DevTools)
  • Verificar rendimiento en la pestaña Rendimiento de DevTools
  • Verificar 60fps en los dispositivos objetivo
  • Contenido visible sin JavaScript
  • Imágenes cargadas de forma perezosa antes de actualizar ScrollTrigger
  • Sin thrashing de layout (evitar animar propiedades de layout)

Integración de Visual QA

  • Animaciones completas antes de las capturas de pantalla
  • El scroll de página completa activa todas las animaciones
  • Las capturas de pantalla capturan el estado final animado
  • Probar en todos los tamaños de viewport

Recursos

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

Skills relacionados