GSAP y Angular

Publicado el 09.01.2021 a las 16:39

GSAP y Angular

GSAP y Angular

GSAP es un increíble librería gratuita para hacer animaciones con JavaScript.


Puedes acceder a su página oficial pulsando aquí


A continuación te explicaré cómo implementar esta librería en Angular 11

Instalando la librería

npm install --save gsap @types/gsap
Puedes acceder al recurso pulsando aquí

Creando las directivas

El ejemplo lo haré usando directivas de Angular para ahorrar repetir código.


  1. En la carpeta src/app creamos una nueva carpeta llamada directives y dentro otra llamada gsap

    mkdir directives\gsap
  2. Dentro de la carpeta anterior creamos un fichero de TypeScript llamado core-animation.directive.ts que contendrá una clase

  3. En el interior del fichero escribimos:

      import {ElementRef, EventEmitter, Input, Output} from '@angular/core';
      import {TimelineMax} from 'gsap';
      
      export class CoreAnimationDirective {
        @Input() duration = 1;
        @Input() delay = 0;
      
        @Output() complete: EventEmitter<null> = new EventEmitter();
        @Output() reverseComplete: EventEmitter<null> = new EventEmitter();
        protected timeline: TimelineMax;
      
        constructor(protected element: ElementRef) {
          this.timeline = new TimelineMax({
              onComplete: _ => this.complete.emit(),
              onReverseComplete: _ => this.reverseComplete.emit(),
              paused:true,
              reversed:true
            });
        }
      
        protected animateIn() {
          if(this.timeline.isActive()) {
            this.timeline.kill();
          }
          this.timeline.play();
        }
      }
      
  4. El constructor de la clase anterior sólo acepta un parámetro, que será el elmento HTML a animar

    Como puedes apreciar, en el constructor encontrarás:

      this.timeline = new TimelineMax({
        onComplete: _ => this.complete.emit(),
        onReverseComplete: _ => this.reverseComplete.emit(),
        paused:true,
        reversed:true
      });
      

    Lo que hago es instanciar un timeline pausado y no reversible con dos callbacks, onComplete y onReverseComplete

  5. Creo el método de clase animateIn

  6. Creo la clase FadeInDirective que será la clase que realmente realizar la animación. Para ello, en la carpeta gsap creamos el fichero fade-in-animation.directive.ts

    Esta nueva clase hereda de la clase anterior CoreAnimationClass

  7. En su interior escribimos:

    import { Directive, OnInit, ElementRef } from '@angular/core';
    import { CoreAnimationDirective } from './core-animation.directive';
    
    @Directive({
      selector: '[fadeInAnimation]'
    })
    export class FadeInAnimationDirective extends CoreAnimationDirective implements OnInit {
      constructor(protected element: ElementRef) {
        super(element);
      }
    
      ngOnInit() {
        // perform animation
        this.animateIn();
      }
    
      protected animateIn() {
        this.timeline.from(this.element.nativeElement, this.duration, {opacity:'0', x:-200, ease:"elastic.out"}, this.delay);
        super.animateIn();
      }
    }
      

    Como hemos dicho en el punto anterior, al heredar de CoreAnimationClass no es necesario definir ningún @Input ni ningún @Output

Aplicando directivas al HTML

  1. Primero necesitamos añadir al AppModule la directiva FadeInDirective

    Para ello, el app.module.ts quedaría:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    
    import {FadeInAnimationDirective} from './directives/gsap/fade-in-animation.directive';
    
    @NgModule({
      declarations: [
        AppComponent,
        FadeInAnimationDirective
      ],
      imports: [
        BrowserModule,
        AppRoutingModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  2. Añadir al app.component.html:

    <h1
      fadeInAnimation
      [duration]="1"
      [delay]="1"
    >
      Primer párrafo
    </h1>
    <h1
      fadeInAnimation
      [duration]="1"
      [delay]="2"
    >
      Segundo párrafo
    </h1>
    
  3. ¡DISTRÚTALO!


GITHUB

Puedes encontrar el ejemplo en mi GitHub

Hasta luego 🖖

Servicios

Software

IoT

Digitalización

Aplicaciones móviles

Consultoría

fjmduran.com v0.2.2