Skip to main content

Implementing Ionic Animations

1. Creating Animations

Example: Basic Animation with Ionic

import { AnimationController } from '@ionic/angular';

const animationController = new AnimationController();
const element = document.querySelector('.my-element');

const animation = animationController.create()
  .addElement(element)
  .fromTo('opacity', '0', '1')
  .duration(300);

animation.play();
Property Description Values Notes
addElement Adds an element to the animation HTMLElement Required for all animations
fromTo Defines start and end values for a property property: string, fromValue: string | number, toValue: string | number Can be called multiple times
duration Animation duration in milliseconds number Default is 300ms
easing Easing function for the animation string Options: 'ease', 'ease-in', 'ease-out', 'ease-in-out'
iterations Number of times to repeat the animation number Default is 1
Note: The AnimationController is part of Ionic's internal animation system and should be used for creating complex animations in Ionic apps.

2. Setting Animation Properties

Property Description Values Notes
duration Duration of the animation in milliseconds number Default is 300ms
easing Easing function to control animation timing ease-in, ease-out, ease-in-out, linear Default is ease-in-out
delay Delay before animation starts in milliseconds number Default is 0ms
iterations Number of times the animation repeats number, infinite Default is 1
direction Animation direction normal, reverse, alternate, alternate-reverse Default is normal

Example: Setting Animation Properties

const animation = new Animation();
animation.duration(500);
animation.easing('ease-in');
animation.delay(100);
animation.iterations(2);
animation.direction('alternate');

3. Using Transform Animations

Property Values Description
transform translateX(100px) Translates the element along the X axis
transform translateY(50px) Translates the element along the Y axis
transform scale(1.5) Scales the element to 1.5x its original size
transform rotate(45deg) Rotates the element 45 degrees

Example: Applying Transform Animation

import { AnimationController } from '@ionic/angular';

const animationController = new AnimationController();
const element = document.querySelector('.my-element');

const animation = animationController.create()
  .addElement(element)
  .fromTo('transform', 'translateX(0)', 'translateX(100px)')
  .duration(500);

animation.play();
Note: Transform animations are hardware-accelerated and performant for UI updates.

4. Implementing Opacity Animations

Property Values Description
opacity 0 to 1 Defines the transparency level of an element. 0 is fully transparent, 1 is fully opaque.

Example: Fade In Animation

import { AnimationController } from '@ionic/angular';

const animationController = new AnimationController();
const fadeAnimation = animationController.create()
  .addElement(document.querySelector('.fade-element'))
  .fromTo('opacity', '0', '1')
  .duration(500);

fadeAnimation.play();

Example: Fade Out Animation

import { AnimationController } from '@ionic/angular';

const animationController = new AnimationController();
const fadeOutAnimation = animationController.create()
  .addElement(document.querySelector('.fade-element'))
  .fromTo('opacity', '1', '0')
  .duration(500);

fadeOutAnimation.play();
Note: Opacity animations are commonly used for entrance and exit transitions in Ionic components.

5. Chaining Animations

Chaining animations in Ionic allows you to sequence multiple animations to create complex motion effects. You can chain animations using the then method or by using the Animation API's built-in chaining capabilities.

Method Description Usage
then() Chains another animation to run after the current one completes.
const animation = ionAnim.create();
animation.then(otherAnimation);
add() Adds another animation to the sequence.
const animation = ionAnim.create();
animation.add(otherAnimation);

Example: Chaining Animations

const ionAnim = require('@ionic/core');
const element = document.querySelector('.my-element');

// Create first animation
const fadeIn = ionAnim.create()
  .addElement(element)
  .fromTo('opacity', '0', '1')
  .duration(500);

// Create second animation
const slideIn = ionAnim.create()
  .addElement(element)
  .fromTo('transform', 'translateX(-100px)', 'translateX(0)')
  .duration(500);

// Chain animations
fadeIn.then(slideIn).play();
Note: Chaining animations is useful for creating complex UI transitions or interactive feedback in Ionic apps.

6. Using Animation Groups

Animation groups in Ionic allow you to orchestrate multiple animations together, enabling complex animation sequences. Groups can be used to run animations in parallel or sequentially.

Property Description Values
animations List of animations to include in the group Array of Animation objects
duration Duration of the animation group in milliseconds Number (optional)
easing Easing function to apply to the group String (e.g., 'ease-in')
delay Delay before starting the animation group in milliseconds Number (optional)

Example: Creating an Animation Group

import { AnimationController } from '@ionic/angular';

const animationController = new AnimationController();
const group = animationController.create();

// Create individual animations
const fadeIn = group.addElement(element).fadeIn();
const slideIn = group.addElement(element).slideInRight();

// Run animations in parallel
group.addAnimation(fadeIn);
group.addAnimation(slideIn);

// Play the group
group.play();

Example: Sequential Animation Group

import { AnimationController } from '@ionic/angular';

const animationController = new AnimationController();
const group = animationController.create();

// Create sequential animations
const fadeOut = group.addElement(element).fadeOut();
const slideOut = group.addElement(element).slideOutLeft();

// Set animations to run sequentially
group.addAnimation(fadeOut);
group.addAnimation(slideOut);

// Play the group
group.play();

7. Controlling Animation Playback

Method Description Parameters Return Type
play() Starts the animation from the beginning None void
pause() Pauses the animation at its current position None void
resume() Resumes the animation from where it was paused None void
stop() Stops the animation and resets to initial state None void
reverse() Plays the animation in reverse direction None void
seek(position) Sets the animation to a specific position (0-1) number - Position between 0 and 1 void

Example: Controlling Animation Playback

const animation = ionAnim.create({
  el: document.querySelector('.my-element'),
  keyframes: [
    { transform: 'translateX(0px)' },
    { transform: 'translateX(100px)' }
  ],
  duration: 1000
});

// Play the animation
animation.play();

// Pause after 500ms
setTimeout(() => {
  animation.pause();
}, 500);

// Resume after another 500ms
setTimeout(() => {
  animation.resume();
}, 1000);

// Stop and reset after 2 seconds
setTimeout(() => {
  animation.stop();
}, 2000);
Note: The seek() method allows precise control over animation timing, useful for creating interactive animations or syncing with user input.

8. Reversing Animations

To reverse an animation in Ionic, you can use the reverse property or method depending on the animation type. This is particularly useful when you want to animate elements back to their original state.

Property/Method Description Usage
reverse Boolean flag to reverse the animation direction reverse: true

Example: Reversing a Slide Animation

const slideAnimation = createAnimation()
  .addElement(element)
  .fromTo('transform', 'translateX(0)', 'translateX(100px)')
  .reverse(true);

slideAnimation.play();
Note: The reverse property works best with animations that have a defined start and end state.

9. Using Animation Callbacks

Animation callbacks in Ionic allow you to execute custom logic at specific points during an animation lifecycle. These are particularly useful for triggering side effects like logging, updating state, or coordinating with other animations.

Callback Description Usage
onStart Called when the animation begins. onStart: () => console.log('Animation started')
onFinish Called when the animation completes. onFinish: () => console.log('Animation finished')
onCancel Called if the animation is cancelled. onCancel: () => console.log('Animation cancelled')

Example: Using Animation Callbacks

import { AnimationController } from '@ionic/angular';

const animationController = new AnimationController();
const element = document.querySelector('.my-element');

const animation = animationController.create()
  .addElement(element)
  .fromTo('opacity', '0', '1')
  .duration(500)
  .onStart(() => console.log('Fade in started'))
  .onFinish(() => console.log('Fade in completed'));

animation.play();
Note: Callbacks are executed in the context of the animation's lifecycle and can be used to synchronize other operations or update UI elements based on animation state.

10. Creating Page Transitions

Property Description Values
ion-page Base component for each page in Ionic <ion-page>
ion-router-outlet Container for routing pages with transitions <ion-router-outlet>
ion-back-button Button to navigate back in history <ion-back-button>

Example: Basic Page Transition Setup

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  template: &#x27;<ion-page>
  <ion-header>
    <ion-toolbar>
      <ion-title>Home</ion-title>
    </ion-toolbar>
  </ion-header>
  <ion-content>
    <ion-button routerLink="/details">Go to Details</ion-button>
  </ion-content>
</ion-page>&#x27;
})
export class HomeComponent {}

Example: Custom Transition with AnimationController

import { AnimationController } from &#x27;@ionic/angular&#x27;;

@Component({
  selector: &#x27;app-details&#x27;,
  template: &#x27;<ion-page>
  <ion-header>
    <ion-toolbar>
      <ion-buttons slot="start">
        <ion-back-button defaultHref="/"></ion-back-button>
      </ion-buttons>
      <ion-title>Details</ion-title>
    </ion-toolbar>
  </ion-header>
  <ion-content>
    <p>Page content</p>
  </ion-content>
</ion-page>&#x27;
})
export class DetailsComponent {
  constructor(private animationCtrl: AnimationController) {}
}
Note: Page transitions in Ionic are handled by the router and can be customized using ion-router-outlet and animation controllers.

Transition Types

  • Slide: Slide in from right to left (default for iOS)
  • Fade: Fade in and out (default for Android)
  • Flip: Flip transition effect
  • Custom: Use AnimationController for custom animations

11. Implementing Gesture-Driven Animations

Example: Basic Pan Gesture Animation

import { IonContent, IonPage } from '@ionic/react';
import { usePanGesture } from '@ionic/react-hooks';

const PanAnimationExample = () => {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);

  const panGesture = usePanGesture({
    onPanStart: () => setIsDragging(true),
    onPanMove: (delta) => {
      setPosition(prev => ({
        x: prev.x + delta.x,
        y: prev.y + delta.y
      }));
    },
    onPanEnd: () => setIsDragging(false)
  });

  return (
    <IonPage>
      <IonContent>
        <div
          style={{
            transform: `translate(${position.x}px, ${position.y}px)`,
            transition: isDragging ? 'none' : 'transform 0.2s ease'
          }}
          ref={panGesture.ref}
        >
          Draggable Element
        </div>
      </IonContent>
    </IonPage>
  );
};

export default PanAnimationExample;
Property Description Values Notes
ref Reference to the DOM element to attach the gesture React.RefObject Required to enable gesture recognition
onPanStart Callback when pan gesture starts () => void Use to update UI state (e.g., isDragging)
onPanMove Callback when pan gesture moves (delta: { x: number; y: number }) => void Use to update position or transform values
onPanEnd Callback when pan gesture ends () => void Use to finalize animation or reset state
Note: The usePanGesture hook is part of the experimental @ionic/react-hooks package and may change in future versions.

Key Concepts

  • Pan gestures are used to detect and respond to swipe or drag interactions.
  • Animations can be controlled by real-time gesture data for a more natural feel.
  • Use CSS transform properties for performance-critical animations.

Was this article helpful?