Animations (애니메이션)
Ionic Animations는 개발자가 특정 프레임워크나 Ionic 앱이 아니어도 플랫폼에 구애받지 않는 방식으로 복잡한 애니메이션을 만들 수 있게 해주는 도구입니다.
출처: 문서
본문
Overview (개요)
효율적인 애니메이션을 만드는 것은 쉬운 일이 아닙니다. 개발자는 사용 가능한 라이브러리와 기기의 하드웨어 리소스에 제약을 받기 때문입니다. 게다가 많은 애니메이션 라이브러리는 JavaScript 기반 접근 방식을 사용해 애니메이션의 확장성을 떨어뜨리고 CPU 시간을 소모할 수 있습니다.
반면 Ionic Animations는 Web Animations API를 사용합니다. 이 API는 애니메이션의 모든 계산과 실행을 브라우저에 맡깁니다. 이 방식을 사용하면 브라우저가 애니메이션을 최적화하고 부드럽게 실행되도록 보장할 수 있습니다. Web Animations를 지원하지 않는 환경에서는 Ionic Animations가 CSS Animations으로 대체(fallback)되며, 이 경우 성능 차이는 무시할 만한 수준입니다.
Installation (설치)
JavaScript
Ionic Core와 JavaScript를 사용하는 개발자는 최신 버전의 @ionic/core를 설치해야 합니다.
import { createAnimation } from 'https://cdn.jsdelivr.net/npm/@ionic/core@latest/dist/esm/index.mjs';
...
const animation = createAnimation()
.addElement(myElementRef)
.duration(1000)
.fromTo('opacity', '1', '0.5');
}
TypeScript
Ionic Core와 TypeScript를 사용하는 개발자는 최신 버전의 @ionic/core를 설치해야 합니다.
import { createAnimation, Animation } from '@ionic/core';
...
const animation: Animation = createAnimation('')
.addElement(myElementRef)
.duration(1000)
.fromTo('opacity', '1', '0.5');
}
Angular
Angular를 사용하는 개발자는 최신 버전의 @ionic/angular를 설치해야 합니다. 애니메이션은 AnimationController 의존성 주입을 통해 만들 수 있습니다.
import { Animation, AnimationController } from '@ionic/angular/lazy';
...
constructor(private animationCtrl: AnimationController) {
const animation: Animation = this.animationCtrl.create()
.addElement(myElementRef)
.duration(1000)
.fromTo('opacity', '1', '0.5');
}
Angular (Standalone)
Angular를 사용하는 개발자는 최신 버전의 @ionic/angular를 설치해야 합니다. 애니메이션은 AnimationController 의존성 주입을 통해 만들 수 있습니다.
import { Animation, AnimationController } from '@ionic/angular';
...
constructor(private animationCtrl: AnimationController) {
const animation: Animation = this.animationCtrl.create()
.addElement(myElementRef)
.duration(1000)
.fromTo('opacity', '1', '0.5');
}
React
React를 사용하는 개발자는 최신 버전의 @ionic/react를 설치해야 합니다. React 래퍼는 베타 버전입니다. 문제가 있으면 GitHub에 보고해 주세요!
import { CreateAnimation, Animation } from '@ionic/react';
...
<CreateAnimation
duration={1000}
fromTo={{
property: 'opacity',
fromValue: '1',
toValue: '0.5'
}}
>
...
</CreateAnimation>
Vue
Ionic Vue를 사용하는 개발자는 최신 버전의 @ionic/vue를 설치해야 합니다.
import { createAnimation } from '@ionic/vue';
import { ref } from 'vue';
...
const myElementRef = ref();
...
const animation = createAnimation()
.addElement(myElementRef.value)
.duration(1000)
.fromTo('opacity', '1', '0.5');
}
Basic Animations (기본 애니메이션)
아래 예제에서는 ion-card 요소의 불투명도(opacity)를 바꾸고 X 축을 따라 왼쪽에서 오른쪽으로 이동시키는 애니메이션을 만들었습니다. 이 애니메이션은 무한히 반복 실행되며, 각 반복은 1500ms 동안 지속됩니다.
기본적으로 모든 Ionic Animations는 play 메서드를 호출할 때까지 일시정지(paused) 상태입니다.
JavaScript
<ion-card id="card">
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>
<script>
var animation = createAnimation()
.addElement(document.querySelector('#card'))
.duration(1500)
.iterations(Infinity)
.fromTo('transform', 'translateX(0px)', 'translateX(100px)')
.fromTo('opacity', '1', '0.2');
</script>
Angular
src/app/example.component.html
<ion-card #card>
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
src/app/example.component.ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
@ViewChild(IonCard, { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;
private animation!: Animation;
constructor(private animationCtrl: AnimationController) {}
ngAfterViewInit() {
this.animation = this.animationCtrl
.create()
.addElement(this.card.nativeElement)
.duration(1500)
.iterations(Infinity)
.fromTo('transform', 'translateX(0px)', 'translateX(100px)')
.fromTo('opacity', '1', '0.2');
}
play() {
this.animation.play();
}
pause() {
this.animation.pause();
}
stop() {
this.animation.stop();
}
}
React
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';
function Example() {
const cardEl = useRef<HTMLIonCardElement | null>(null);
const animation = useRef<Animation | null>(null);
useEffect(() => {
if (animation.current === null) {
animation.current = createAnimation()
.addElement(cardEl.current!)
.duration(1500)
.iterations(Infinity)
.fromTo('transform', 'translateX(0px)', 'translateX(100px)')
.fromTo('opacity', '1', '0.2');
}
}, [cardEl]);
const play = () => {
animation.current?.play();
};
const pause = () => {
animation.current?.pause();
};
const stop = () => {
animation.current?.stop();
};
return (
<>
<IonCard ref={cardEl}>
<IonCardContent>Card</IonCardContent>
</IonCard>
<IonButton onClick={play}>Play</IonButton>
<IonButton onClick={pause}>Pause</IonButton>
<IonButton onClick={stop}>Stop</IonButton>
</>
);
}
export default Example;
Vue
<template>
<ion-card ref="cardEl">
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button @click="play()">Play</ion-button>
<ion-button @click="pause()">Pause</ion-button>
<ion-button @click="stop()">Stop</ion-button>
</template>
<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';
const cardEl = ref(null);
let animation: Animation;
onMounted(() => {
animation = createAnimation()
.addElement(cardEl.value.$el)
.duration(1500)
.iterations(Infinity)
.fromTo('transform', 'translateX(0px)', 'translateX(100px)')
.fromTo('opacity', '1', '0.2');
});
const play = () => animation.play();
const pause = () => animation.pause();
const stop = () => animation.stop();
</script>
Keyframe Animations (키프레임 애니메이션)
Ionic Animations를 사용하면 키프레임으로 애니메이션의 중간 단계를 제어할 수 있습니다. 이때 유효한 CSS 속성은 무엇이든 사용할 수 있고, 값으로 CSS Variables까지 사용할 수 있습니다.
하이픈으로 연결된 CSS 속성은 키프레임을 작성할 때 카멜 케이스(camel case)로 써야 합니다. 예를 들어 border-radius는 borderRadius로 작성해야 합니다. 이 규칙은 fromTo(), from(), to() 메서드에도 동일하게 적용됩니다.
JavaScript
<ion-card id="card" style="width: 80px; --width: 160px;">
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>
<script>
var animation = createAnimation()
.addElement(document.querySelector('#card'))
.duration(3000)
.iterations(Infinity)
.keyframes([
{ offset: 0, width: '80px' },
{ offset: 0.72, width: 'var(--width)' },
{ offset: 1, width: '240px' },
]);
</script>
Angular
src/app/example.component.html
<ion-card #card style="width: 80px; --width: 160px;">
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
src/app/example.component.ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
@ViewChild(IonCard, { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;
private animation!: Animation;
constructor(private animationCtrl: AnimationController) {}
ngAfterViewInit() {
this.animation = this.animationCtrl
.create()
.addElement(this.card.nativeElement)
.duration(3000)
.iterations(Infinity)
.keyframes([
{ offset: 0, width: '80px' },
{ offset: 0.72, width: 'var(--width)' },
{ offset: 1, width: '240px' },
]);
}
play() {
this.animation.play();
}
pause() {
this.animation.pause();
}
stop() {
this.animation.stop();
}
}
React
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';
function Example() {
const cardEl = useRef<HTMLIonCardElement | null>(null);
const animation = useRef<Animation | null>(null);
useEffect(() => {
if (animation.current === null) {
animation.current = createAnimation()
.addElement(cardEl.current!)
.duration(3000)
.iterations(Infinity)
.keyframes([
{ offset: 0, width: '80px' },
{ offset: 0.72, width: 'var(--width)' },
{ offset: 1, width: '240px' },
]);
}
}, [cardEl]);
const play = () => {
animation.current?.play();
};
const pause = () => {
animation.current?.pause();
};
const stop = () => {
animation.current?.stop();
};
return (
<>
<IonCard ref={cardEl} style={{ width: '80px', '--width': '160px' } as React.CSSProperties}>
<IonCardContent>Card</IonCardContent>
</IonCard>
<IonButton onClick={play}>Play</IonButton>
<IonButton onClick={pause}>Pause</IonButton>
<IonButton onClick={stop}>Stop</IonButton>
</>
);
}
export default Example;
Vue
<template>
<ion-card ref="cardEl">
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button @click="play()">Play</ion-button>
<ion-button @click="pause()">Pause</ion-button>
<ion-button @click="stop()">Stop</ion-button>
</template>
<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';
const cardEl = ref(null);
let animation: Animation;
onMounted(() => {
animation = createAnimation()
.addElement(cardEl.value.$el)
.duration(3000)
.iterations(Infinity)
.keyframes([
{ offset: 0, width: '80px' },
{ offset: 0.72, width: 'var(--width)' },
{ offset: 1, width: '240px' },
]);
});
const play = () => animation.play();
const pause = () => animation.pause();
const stop = () => animation.stop();
</script>
<style>
ion-card {
width: 80px;
--width: 160px;
}
</style>
위 예제에서 card 요소는 처음 너비에서 --width 변수가 정의하는 너비로 전환되고, 이어서 마지막 너비로 전환됩니다.
각 키프레임 객체는 offset 속성을 포함합니다. offset은 키프레임 단계를 정의하는 0과 1 사이의 값입니다. 오프셋 값은 오름차순이어야 하며 중복될 수 없습니다.
Grouped Animations (그룹 애니메이션)
여러 요소를 동시에 애니메이션하면서 단일 상위(parent) 애니메이션 객체로 제어할 수 있습니다. 자식 애니메이션은 별도로 지정하지 않는 한 duration, easing, iterations 같은 속성을 상속받습니다. 상위 애니메이션의 onFinish 콜백은 모든 자식 애니메이션이 완료될 때까지 호출되지 않습니다.
이 예제는 단일 상위 애니메이션이 제어하는 3개의 자식 애니메이션을 보여줍니다. cardA와 cardB 애니메이션은 상위 애니메이션의 duration인 2000ms를 상속받지만, cardC 애니메이션은 명시적으로 설정되었기 때문에 duration이 5000ms입니다.
JavaScript
<ion-card id="card-a">
<ion-card-content>Card 1</ion-card-content>
</ion-card>
<ion-card id="card-b">
<ion-card-content>Card 2</ion-card-content>
</ion-card>
<ion-card id="card-c">
<ion-card-content>Card 3</ion-card-content>
</ion-card>
<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>
<script>
const cardA = createAnimation()
.addElement(document.querySelector('#card-a'))
.keyframes([
{ offset: 0, transform: 'scale(1) rotate(0)' },
{ offset: 0.5, transform: 'scale(1.5) rotate(45deg)' },
{ offset: 1, transform: 'scale(1) rotate(0) ' },
]);
const cardB = createAnimation()
.addElement(document.querySelector('#card-b'))
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '1' },
{ offset: 0.5, transform: 'scale(1.5)', opacity: '0.3' },
{ offset: 1, transform: 'scale(1)', opacity: '1' },
]);
const cardC = createAnimation()
.addElement(document.querySelector('#card-c'))
.duration(5000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '0.5' },
{ offset: 0.5, transform: 'scale(0.5)', opacity: '1' },
{ offset: 1, transform: 'scale(1)', opacity: '0.5' },
]);
var animation = createAnimation().duration(2000).iterations(Infinity).addAnimation([cardA, cardB, cardC]);
</script>
Angular
src/app/example.component.html
<ion-card>
<ion-card-content>Card 1</ion-card-content>
</ion-card>
<ion-card>
<ion-card-content>Card 2</ion-card-content>
</ion-card>
<ion-card>
<ion-card-content>Card 3</ion-card-content>
</ion-card>
<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
src/app/example.component.ts
import { Component, ElementRef, ViewChildren } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { QueryList } from '@angular/core';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
@ViewChildren(IonCard, { read: ElementRef }) cardElements!: QueryList<ElementRef<HTMLIonCardElement>>;
private animation!: Animation;
constructor(private animationCtrl: AnimationController) {}
ngAfterViewInit() {
const cardA = this.animationCtrl
.create()
.addElement(this.cardElements.get(0)!.nativeElement)
.keyframes([
{ offset: 0, transform: 'scale(1) rotate(0)' },
{ offset: 0.5, transform: 'scale(1.5) rotate(45deg)' },
{ offset: 1, transform: 'scale(1) rotate(0)' },
]);
const cardB = this.animationCtrl
.create()
.addElement(this.cardElements.get(1)!.nativeElement)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '1' },
{ offset: 0.5, transform: 'scale(1.5)', opacity: '0.3' },
{ offset: 1, transform: 'scale(1)', opacity: '1' },
]);
const cardC = this.animationCtrl
.create()
.addElement(this.cardElements.get(2)!.nativeElement)
.duration(5000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '0.5' },
{ offset: 0.5, transform: 'scale(0.5)', opacity: '1' },
{ offset: 1, transform: 'scale(1)', opacity: '0.5' },
]);
this.animation = this.animationCtrl
.create()
.duration(2000)
.iterations(Infinity)
.addAnimation([cardA, cardB, cardC].filter(Boolean) as Animation[]);
}
play() {
this.animation.play();
}
pause() {
this.animation.pause();
}
stop() {
this.animation.stop();
}
}
React
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';
function Example() {
const cardAEl = useRef<HTMLIonCardElement | null>(null);
const cardBEl = useRef<HTMLIonCardElement | null>(null);
const cardCEl = useRef<HTMLIonCardElement | null>(null);
const animation = useRef<Animation | null>(null);
useEffect(() => {
if (animation.current === null) {
const cardA = createAnimation()
.addElement(cardAEl.current!)
.keyframes([
{ offset: 0, transform: 'scale(1) rotate(0)' },
{ offset: 0.5, transform: 'scale(1.5) rotate(45deg)' },
{ offset: 1, transform: 'scale(1) rotate(0) ' },
]);
const cardB = createAnimation()
.addElement(cardBEl.current!)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '1' },
{ offset: 0.5, transform: 'scale(1.5)', opacity: '0.3' },
{ offset: 1, transform: 'scale(1)', opacity: '1' },
]);
const cardC = createAnimation()
.addElement(cardCEl.current!)
.duration(5000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '0.5' },
{ offset: 0.5, transform: 'scale(0.5)', opacity: '1' },
{ offset: 1, transform: 'scale(1)', opacity: '0.5' },
]);
animation.current = createAnimation().duration(2000).iterations(Infinity).addAnimation([cardA, cardB, cardC]);
}
}, [cardAEl, cardBEl, cardCEl]);
const play = () => {
animation.current?.play();
};
const pause = () => {
animation.current?.pause();
};
const stop = () => {
animation.current?.stop();
};
return (
<>
<IonCard ref={cardAEl}>
<IonCardContent>Card 1</IonCardContent>
</IonCard>
<IonCard ref={cardBEl}>
<IonCardContent>Card 2</IonCardContent>
</IonCard>
<IonCard ref={cardCEl}>
<IonCardContent>Card 3</IonCardContent>
</IonCard>
<IonButton onClick={play}>Play</IonButton>
<IonButton onClick={pause}>Pause</IonButton>
<IonButton onClick={stop}>Stop</IonButton>
</>
);
}
export default Example;
Vue
<template>
<ion-card ref="cardAEl">
<ion-card-content>Card 1</ion-card-content>
</ion-card>
<ion-card ref="cardBEl">
<ion-card-content>Card 2</ion-card-content>
</ion-card>
<ion-card ref="cardCEl">
<ion-card-content>Card 3</ion-card-content>
</ion-card>
<ion-button @click="play()">Play</ion-button>
<ion-button @click="pause()">Pause</ion-button>
<ion-button @click="stop()">Stop</ion-button>
</template>
<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';
const cardAEl = ref(null);
const cardBEl = ref(null);
const cardCEl = ref(null);
let animation: Animation;
onMounted(() => {
const cardA = createAnimation()
.addElement(cardAEl.value.$el)
.keyframes([
{ offset: 0, transform: 'scale(1) rotate(0)' },
{ offset: 0.5, transform: 'scale(1.5) rotate(45deg)' },
{ offset: 1, transform: 'scale(1) rotate(0) ' },
]);
const cardB = createAnimation()
.addElement(cardBEl.value.$el)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '1' },
{ offset: 0.5, transform: 'scale(1.5)', opacity: '0.3' },
{ offset: 1, transform: 'scale(1)', opacity: '1' },
]);
const cardC = createAnimation()
.addElement(cardCEl.value.$el)
.duration(5000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '0.5' },
{ offset: 0.5, transform: 'scale(0.5)', opacity: '1' },
{ offset: 1, transform: 'scale(1)', opacity: '0.5' },
]);
animation = createAnimation().duration(2000).iterations(Infinity).addAnimation([cardA, cardB, cardC]);
});
const play = () => animation.play();
const pause = () => animation.pause();
const stop = () => animation.stop();
</script>
Before and After Hooks (시작 전/후 훅)
Ionic Animations는 애니메이션이 실행되기 전과 완료된 후에 요소를 변경할 수 있는 훅을 제공합니다. 이 훅들은 DOM 읽기와 쓰기를 수행하거나 클래스와 인라인 스타일을 추가/제거하는 데 사용할 수 있습니다.
이 예제에서는 애니메이션이 시작되기 전에 card의 배경색을 75% 반전시키는 인라인 filter를 설정합니다. 애니메이션이 끝나면 요소의 박스 그림자가 rgba(255, 0, 50, 0.4) 0px 4px 16px 6px, 즉 붉은 빛으로 설정되고 인라인 filter는 제거됩니다. 박스 그림자를 제거하고 filter와 함께 다시 재생하려면 애니메이션을 중지(stop)해야 합니다.
훅의 전체 목록은 Methods를 참고하세요.
JavaScript
<ion-card id="card">
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>
<script>
var animation = createAnimation()
.addElement(document.querySelector('#card'))
.duration(2000)
.beforeStyles({
filter: 'invert(75%)',
})
.beforeClearStyles(['box-shadow'])
.afterStyles({
'box-shadow': 'rgba(255, 0, 50, 0.4) 0px 4px 16px 6px',
})
.afterClearStyles(['filter'])
.keyframes([
{ offset: 0, transform: 'scale(1)' },
{ offset: 0.5, transform: 'scale(1.5)' },
{ offset: 1, transform: 'scale(1)' },
]);
</script>
Angular
src/app/example.component.html
<ion-card>
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
src/app/example.component.ts
import { Component, ElementRef, ViewChildren } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { QueryList } from '@angular/core';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
@ViewChildren(IonCard, { read: ElementRef }) cardElements!: QueryList<ElementRef<HTMLIonCardElement>>;
private animation!: Animation;
constructor(private animationCtrl: AnimationController) {}
ngAfterViewInit() {
const cardEl = this.cardElements.get(0);
const card = cardEl
? this.animationCtrl
.create()
.addElement(cardEl.nativeElement)
.duration(2000)
.beforeStyles({
filter: 'invert(75%)',
})
.beforeClearStyles(['box-shadow'])
.afterStyles({
'box-shadow': 'rgba(255, 0, 50, 0.4) 0px 4px 16px 6px',
})
.afterClearStyles(['filter'])
.keyframes([
{ offset: 0, transform: 'scale(1)' },
{ offset: 0.5, transform: 'scale(1.5)' },
{ offset: 1, transform: 'scale(1)' },
])
: null;
if (card) {
this.animation = this.animationCtrl.create().duration(2000).addAnimation([card]);
}
}
play() {
this.animation.play();
}
pause() {
this.animation.pause();
}
stop() {
this.animation.stop();
}
}
React
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';
function Example() {
const cardEl = useRef<HTMLIonCardElement | null>(null);
const card = useRef<Animation>();
useEffect(() => {
if (!card.current) {
card.current = createAnimation()
.addElement(cardEl.current!)
.duration(2000)
.beforeStyles({
filter: 'invert(75%)',
})
.beforeClearStyles(['box-shadow'])
.afterStyles({
'box-shadow': 'rgba(255, 0, 50, 0.4) 0px 4px 16px 6px',
})
.afterClearStyles(['filter'])
.keyframes([
{ offset: 0, transform: 'scale(1)' },
{ offset: 0.5, transform: 'scale(1.5)' },
{ offset: 1, transform: 'scale(1)' },
]);
}
}, [cardEl]);
const play = async () => {
await card.current?.play();
};
const pause = () => {
card.current?.pause();
};
const stop = () => {
card.current?.stop();
};
return (
<>
<IonCard ref={cardEl}>
<IonCardContent>Card</IonCardContent>
</IonCard>
<IonButton id="play" onClick={play}>
Play
</IonButton>
<IonButton id="pause" onClick={pause}>
Pause
</IonButton>
<IonButton id="stop" onClick={stop}>
Stop
</IonButton>
</>
);
}
export default Example;
Vue
<template>
<ion-card ref="cardEl">
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button @click="play()">Play</ion-button>
<ion-button @click="pause()">Pause</ion-button>
<ion-button @click="stop()">Stop</ion-button>
</template>
<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';
const cardEl = ref(null);
let card: Animation | undefined;
onMounted(() => {
card = createAnimation()
.addElement(cardEl.value.$el)
.duration(2000)
.beforeStyles({
filter: 'invert(75%)',
})
.beforeClearStyles(['box-shadow'])
.afterStyles({
'box-shadow': 'rgba(255, 0, 50, 0.4) 0px 4px 16px 6px',
})
.afterClearStyles(['filter'])
.keyframes([
{ offset: 0, transform: 'scale(1)' },
{ offset: 0.5, transform: 'scale(1.5)' },
{ offset: 1, transform: 'scale(1)' },
]);
});
const play = async () => {
await card.play();
};
const pause = () => {
card?.pause();
};
const stop = () => {
card?.stop();
};
</script>
Chained Animations (연결 애니메이션)
애니메이션은 연결(chaining)해서 차례로 실행할 수 있습니다. play 메서드는 애니메이션이 완료될 때 resolve되는 Promise를 반환합니다.
JavaScript
<ion-card id="card-a">
<ion-card-content>Card 1</ion-card-content>
</ion-card>
<ion-card id="card-b">
<ion-card-content>Card 2</ion-card-content>
</ion-card>
<ion-card id="card-c">
<ion-card-content>Card 3</ion-card-content>
</ion-card>
<ion-button onclick="play()">Play</ion-button>
<ion-button onclick="pause()">Pause</ion-button>
<ion-button onclick="stop()">Stop</ion-button>
<script>
const cardA = createAnimation()
.addElement(document.querySelector('#card-a'))
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1) rotate(0)' },
{ offset: 0.5, transform: 'scale(1.2) rotate(45deg)' },
{ offset: 1, transform: 'scale(1) rotate(0)' },
]);
const cardB = createAnimation()
.addElement(document.querySelector('#card-b'))
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '1' },
{ offset: 0.5, transform: 'scale(1.2)', opacity: '0.3' },
{ offset: 1, transform: 'scale(1)', opacity: '1' },
]);
const cardC = createAnimation()
.addElement(document.querySelector('#card-c'))
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '0.5' },
{ offset: 0.5, transform: 'scale(0.8)', opacity: '1' },
{ offset: 1, transform: 'scale(1)', opacity: '0.5' },
]);
async function play() {
await cardA.play();
await cardB.play();
await cardC.play();
}
function pause() {
cardA.pause();
cardB.pause();
cardC.pause();
}
function stop() {
cardA.stop();
cardB.stop();
cardC.stop();
}
</script>
Angular
src/app/example.component.html
<ion-card>
<ion-card-content>Card 1</ion-card-content>
</ion-card>
<ion-card>
<ion-card-content>Card 2</ion-card-content>
</ion-card>
<ion-card>
<ion-card-content>Card 3</ion-card-content>
</ion-card>
<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
src/app/example.component.ts
import { Component, ElementRef, ViewChildren } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { QueryList } from '@angular/core';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
@ViewChildren(IonCard, { read: ElementRef }) cardElements!: QueryList<ElementRef<HTMLIonCardElement>>;
private cardA!: Animation | null;
private cardB!: Animation | null;
private cardC!: Animation | null;
constructor(private animationCtrl: AnimationController) {}
ngAfterViewInit() {
const cardElA = this.cardElements.get(0);
const cardElB = this.cardElements.get(1);
const cardElC = this.cardElements.get(2);
this.cardA = cardElA
? this.animationCtrl
.create()
.addElement(cardElA.nativeElement)
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1) rotate(0)' },
{ offset: 0.5, transform: 'scale(1.2) rotate(45deg)' },
{ offset: 1, transform: 'scale(1) rotate(0)' },
])
: null;
this.cardB = cardElB
? this.animationCtrl
.create()
.addElement(cardElB.nativeElement)
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '1' },
{ offset: 0.5, transform: 'scale(1.2)', opacity: '0.3' },
{ offset: 1, transform: 'scale(1)', opacity: '1' },
])
: null;
this.cardC = cardElC
? this.animationCtrl
.create()
.addElement(cardElC.nativeElement)
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '0.5' },
{ offset: 0.5, transform: 'scale(0.8)', opacity: '1' },
{ offset: 1, transform: 'scale(1)', opacity: '0.5' },
])
: null;
}
async play() {
await this.cardA?.play();
await this.cardB?.play();
await this.cardC?.play();
}
pause() {
this.cardA?.pause();
this.cardB?.pause();
this.cardC?.pause();
}
async stop() {
await this.cardA?.stop();
await this.cardB?.stop();
await this.cardC?.stop();
}
}
React
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';
function Example() {
const cardAEl = useRef<HTMLIonCardElement | null>(null);
const cardBEl = useRef<HTMLIonCardElement | null>(null);
const cardCEl = useRef<HTMLIonCardElement | null>(null);
const cardA = useRef<Animation>();
const cardB = useRef<Animation>();
const cardC = useRef<Animation>();
useEffect(() => {
if (!cardA.current) {
cardA.current = createAnimation()
.addElement(cardAEl.current!)
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1) rotate(0)' },
{ offset: 0.5, transform: 'scale(1.2) rotate(45deg)' },
{ offset: 1, transform: 'scale(1) rotate(0)' },
]);
}
if (!cardB.current) {
cardB.current = createAnimation()
.addElement(cardBEl.current!)
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '1' },
{ offset: 0.5, transform: 'scale(1.2)', opacity: '0.3' },
{ offset: 1, transform: 'scale(1)', opacity: '1' },
]);
}
if (!cardC.current) {
cardC.current = createAnimation()
.addElement(cardCEl.current!)
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '0.5' },
{ offset: 0.5, transform: 'scale(0.8)', opacity: '1' },
{ offset: 1, transform: 'scale(1)', opacity: '0.5' },
]);
}
}, [cardAEl, cardBEl, cardCEl]);
const play = async () => {
await cardA.current?.play();
await cardB.current?.play();
await cardC.current?.play();
};
const pause = () => {
cardA.current?.pause();
cardB.current?.pause();
cardC.current?.pause();
};
const stop = () => {
cardA.current?.stop();
cardB.current?.stop();
cardC.current?.stop();
};
return (
<>
<IonCard ref={cardAEl}>
<IonCardContent>Card 1</IonCardContent>
</IonCard>
<IonCard ref={cardBEl}>
<IonCardContent>Card 2</IonCardContent>
</IonCard>
<IonCard ref={cardCEl}>
<IonCardContent>Card 3</IonCardContent>
</IonCard>
<IonButton onClick={play}>Play</IonButton>
<IonButton onClick={pause}>Pause</IonButton>
<IonButton onClick={stop}>Stop</IonButton>
</>
);
}
export default Example;
Vue
<template>
<ion-card ref="cardAEl">
<ion-card-content>Card 1</ion-card-content>
</ion-card>
<ion-card ref="cardBEl">
<ion-card-content>Card 2</ion-card-content>
</ion-card>
<ion-card ref="cardCEl">
<ion-card-content>Card 3</ion-card-content>
</ion-card>
<ion-button @click="play()">Play</ion-button>
<ion-button @click="pause()">Pause</ion-button>
<ion-button @click="stop()">Stop</ion-button>
</template>
<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';
const cardAEl = ref(null);
const cardBEl = ref(null);
const cardCEl = ref(null);
let cardA: Animation | undefined;
let cardB: Animation | undefined;
let cardC: Animation | undefined;
onMounted(() => {
cardA = createAnimation()
.addElement(cardAEl.value.$el)
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1) rotate(0)' },
{ offset: 0.5, transform: 'scale(1.2) rotate(45deg)' },
{ offset: 1, transform: 'scale(1) rotate(0)' },
]);
cardB = createAnimation()
.addElement(cardBEl.value.$el)
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '1' },
{ offset: 0.5, transform: 'scale(1.2)', opacity: '0.3' },
{ offset: 1, transform: 'scale(1)', opacity: '1' },
]);
cardC = createAnimation()
.addElement(cardCEl.value.$el)
.fill('none')
.duration(1000)
.keyframes([
{ offset: 0, transform: 'scale(1)', opacity: '0.5' },
{ offset: 0.5, transform: 'scale(0.8)', opacity: '1' },
{ offset: 1, transform: 'scale(1)', opacity: '0.5' },
]);
});
const play = async () => {
await cardA?.play();
await cardB?.play();
await cardC?.play();
};
const pause = () => {
cardA?.pause();
cardB?.pause();
cardC?.pause();
};
const stop = () => {
cardA?.stop();
cardB?.stop();
cardC?.stop();
};
</script>
Gesture Animations (제스처 애니메이션)
Ionic Animations는 Ionic Gestures와 자연스럽게 통합되어, 개발자가 강력한 제스처 기반 애니메이션을 만들 수 있게 해줍니다.
아래 예제에서는 card 요소를 따라 드래그할 수 있는 트랙(track)을 만듭니다. animation 객체는 card 요소를 왼쪽 또는 오른쪽으로 움직이는 역할을 하고, gesture 객체는 animation 객체에 어느 방향으로 움직일지 지시합니다.
JavaScript
<div class="container">
<div class="track">
<ion-card id="card" button="true">
<ion-card-content>Card</ion-card-content>
</ion-card>
</div>
</div>
<p>Drag the square along the track.</p>
<style>
.container {
display: flex;
}
.track {
width: 344px;
background: var(--ion-color-medium);
padding: 16px;
}
ion-card {
width: 100px;
box-shadow: none;
margin: 0px;
}
</style>
<script>
let initialStep = 0;
let started = false;
const card = document.querySelector('ion-card');
/**
* The track is 344px wide.
* The card is 100px wide.
* We want 16px of margin on each end of the track.
*/
const MAX_TRANSLATE = 344 - 100 - 32;
const animation = createAnimation()
.addElement(card)
.duration(1000)
.fromTo('transform', 'translateX(0)', `translateX(${MAX_TRANSLATE}px)`);
const gesture = createGesture({
el: card,
threshold: 0,
gestureName: 'card-drag',
onMove: (event) => onMove(event),
onEnd: (event) => onEnd(event),
});
gesture.enable(true);
var onMove = (event) => {
if (!started) {
animation.progressStart();
started = true;
}
animation.progressStep(getStep(event));
};
var onEnd = (event) => {
if (!started) {
return;
}
gesture.enable(false);
const step = getStep(event);
const shouldComplete = step > 0.5;
animation.progressEnd(shouldComplete ? 1 : 0, step).onFinish(() => {
gesture.enable(true);
});
initialStep = shouldComplete ? MAX_TRANSLATE : 0;
started = false;
};
var clamp = (min, n, max) => {
return Math.max(min, Math.min(n, max));
};
var getStep = (event) => {
const delta = initialStep + event.deltaX;
return clamp(0, delta / MAX_TRANSLATE, 1);
};
</script>
Angular
src/app/example.component.html
<div class="container">
<div class="track">
<ion-card id="card" button="true">
<ion-card-content>Card</ion-card-content>
</ion-card>
</div>
<p>Drag the square along the track.</p>
</div>
src/app/example.component.ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { AnimationController, GestureController, IonCard, IonCardContent } from '@ionic/angular';
import type { Animation, Gesture, GestureDetail } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonCard, IonCardContent],
})
export class ExampleComponent {
@ViewChild(IonCard, { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;
private animation!: Animation;
private gesture!: Gesture;
private started = false;
private initialStep = 0;
/**
* The track is 344px wide.
* The card is 100px wide.
* We want 16px of margin on each end of the track.
*/
private readonly MAX_TRANSLATE = 344 - 100 - 32;
constructor(
private animationCtrl: AnimationController,
private gestureCtrl: GestureController
) {}
private onMove(event: GestureDetail) {
if (!this.started) {
this.animation.progressStart();
this.started = true;
}
this.animation.progressStep(this.getStep(event));
}
private onEnd(event: GestureDetail) {
if (!this.started) {
return;
}
this.gesture.enable(false);
const step = this.getStep(event);
const shouldComplete = step > 0.5;
this.animation.progressEnd(shouldComplete ? 1 : 0, step).onFinish(() => {
this.gesture.enable(true);
});
this.initialStep = shouldComplete ? this.MAX_TRANSLATE : 0;
this.started = false;
}
private clamp(min: number, n: number, max: number) {
return Math.max(min, Math.min(n, max));
}
private getStep(event: GestureDetail) {
const delta = this.initialStep + event.deltaX;
return this.clamp(0, delta / this.MAX_TRANSLATE, 1);
}
ngAfterViewInit() {
this.animation = this.animationCtrl
.create()
.addElement(this.card.nativeElement)
.duration(1000)
.fromTo('transform', 'translateX(0)', `translateX(${this.MAX_TRANSLATE}px)`);
const gesture = (this.gesture = this.gestureCtrl.create({
el: this.card.nativeElement,
threshold: 0,
gestureName: 'card-drag',
onMove: (event) => this.onMove(event),
onEnd: (event) => this.onEnd(event),
}));
gesture.enable(true);
}
}
src/app/example.component.css
.container {
flex-direction: column;
}
.track {
width: 344px;
background: var(--ion-color-medium);
padding: 16px;
}
ion-card {
width: 100px;
box-shadow: none;
margin: 0px;
}
React
src/main.tsx
import React, { useEffect, useRef } from 'react';
import { IonCard, IonCardContent, createAnimation, createGesture } from '@ionic/react';
import type { Animation, Gesture, GestureDetail } from '@ionic/react';
import './main.css';
function Example() {
const cardEl = useRef<HTMLIonCardElement | null>(null);
const animation = useRef<Animation | null>(null);
const gesture = useRef<Gesture | null>(null);
const initialStep = useRef<number>(0);
const started = useRef<boolean>(false);
useEffect(() => {
if (animation.current === null) {
/**
* The track is 344px wide.
* The card is 100px wide.
* We want 16px of margin on each end of the track.
*/
const MAX_TRANSLATE = 344 - 100 - 32;
animation.current = createAnimation()
.addElement(cardEl.current!)
.duration(1000)
.fromTo('transform', 'translateX(0)', `translateX(${MAX_TRANSLATE}px)`);
gesture.current = createGesture({
el: cardEl.current!,
threshold: 0,
gestureName: 'card-drag',
onMove: (event) => onMove(event),
onEnd: (event) => onEnd(event),
});
gesture.current.enable(true);
const onMove = (event: GestureDetail) => {
if (!started.current) {
animation.current!.progressStart();
started.current = true;
}
animation.current!.progressStep(getStep(event));
};
const onEnd = (event: GestureDetail) => {
if (!started.current) {
return;
}
gesture.current!.enable(false);
const step = getStep(event);
const shouldComplete = step > 0.5;
animation.current!.progressEnd(shouldComplete ? 1 : 0, step).onFinish(() => {
gesture.current!.enable(true);
});
initialStep.current = shouldComplete ? MAX_TRANSLATE : 0;
started.current = false;
};
const clamp = (min: number, n: number, max: number) => {
return Math.max(min, Math.min(n, max));
};
const getStep = (event: GestureDetail) => {
const delta = initialStep.current + event.deltaX;
return clamp(0, delta / MAX_TRANSLATE, 1);
};
}
}, [cardEl]);
return (
<>
<div className="container">
<div className="track">
<IonCard id="card" button={true} ref={cardEl}>
<IonCardContent>Card</IonCardContent>
</IonCard>
</div>
<p>Drag the square along the track.</p>
</div>
</>
);
}
export default Example;
src/main.css
.container {
flex-direction: column;
}
.track {
width: 344px;
background: var(--ion-color-medium);
padding: 16px;
}
ion-card {
width: 100px;
box-shadow: none;
margin: 0px;
}
Vue
<template>
<div class="container">
<div class="track">
<ion-card id="card" button="true" ref="cardEl">
<ion-card-content>Card</ion-card-content>
</ion-card>
</div>
<p>Drag the square along the track.</p>
</div>
</template>
<script setup lang="ts">
import { IonCard, IonCardContent, createAnimation, createGesture } from '@ionic/vue';
import type { GestureDetail } from '@ionic/vue';
import { ref, onMounted } from 'vue';
const cardEl = ref(null);
onMounted(() => {
let initialStep = 0;
let started = false;
/**
* The track is 344px wide.
* The card is 100px wide.
* We want 16px of margin on each end of the track.
*/
const MAX_TRANSLATE = 344 - 100 - 32;
const animation = createAnimation()
.addElement(cardEl.value.$el)
.duration(1000)
.fromTo('transform', 'translateX(0)', `translateX(${MAX_TRANSLATE}px)`);
const gesture = createGesture({
el: cardEl.value.$el,
threshold: 0,
gestureName: 'card-drag',
onMove: (event) => onMove(event),
onEnd: (event) => onEnd(event),
});
gesture.enable(true);
const onMove = (event: GestureDetail) => {
if (!started) {
animation.progressStart();
started = true;
}
animation.progressStep(getStep(event));
};
const onEnd = (event: GestureDetail) => {
if (!started) {
return;
}
gesture.enable(false);
const step = getStep(event);
const shouldComplete = step > 0.5;
animation.progressEnd(shouldComplete ? 1 : 0, step).onFinish(() => {
gesture.enable(true);
});
initialStep = shouldComplete ? MAX_TRANSLATE : 0;
started = false;
};
const clamp = (min: number, n: number, max: number) => {
return Math.max(min, Math.min(n, max));
};
const getStep = (event: GestureDetail) => {
const delta = initialStep + event.deltaX;
return clamp(0, delta / MAX_TRANSLATE, 1);
};
});
</script>
<style scoped>
.container {
flex-direction: column;
}
.track {
width: 344px;
background: var(--ion-color-medium);
padding: 16px;
}
ion-card {
width: 100px;
box-shadow: none;
margin: 0px;
}
</style>
Preference-Based Animations (선호도 기반 애니메이션)
개발자는 CSS Variables를 사용해 prefers-reduced-motion이나 prefers-color-scheme 같은 사용자 선호도에 맞게 애니메이션을 조정할 수도 있습니다.
이 방식은 처음 애니메이션을 만들 때 모든 지원 브라우저에서 동작합니다. 대부분의 브라우저는 CSS Variables가 변할 때 키프레임 애니메이션을 동적으로 업데이트할 수도 있습니다.
Safari는 현재 키프레임 애니메이션을 동적으로 업데이트하는 것을 지원하지 않습니다. Safari에서 이런 지원이 필요한 개발자는 MediaQueryList.addListener()를 사용할 수 있습니다.
JavaScript
<ion-card id="card">
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>
<script>
var animation = createAnimation()
.addElement(document.querySelector('#card'))
.duration(1500)
.iterations(Infinity)
.direction('alternate')
.fromTo('background', 'blue', 'var(--background)');
</script>
<style>
ion-card {
color: white;
opacity: 0.5;
background: blue;
margin: 10px;
--background: red;
}
@media (prefers-color-scheme: dark) {
ion-card {
--background: green;
}
}
</style>
Angular
src/app/example.component.html
<ion-card #card>
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
src/app/example.component.ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['./example.component.css'],
imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
@ViewChild(IonCard, { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;
private animation!: Animation;
constructor(private animationCtrl: AnimationController) {}
ngAfterViewInit() {
this.animation = this.animationCtrl
.create()
.addElement(this.card.nativeElement)
.duration(1500)
.iterations(Infinity)
.direction('alternate')
.fromTo('background', 'blue', 'var(--background)');
}
play() {
this.animation.play();
}
pause() {
this.animation.pause();
}
stop() {
this.animation.stop();
}
}
src/app/example.component.css
ion-card {
color: white;
opacity: 0.5;
background: blue;
margin: 10px;
--background: red;
}
@media (prefers-color-scheme: dark) {
ion-card {
--background: green;
}
}
React
src/main.tsx
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';
import './main.css';
function Example() {
const cardEl = useRef<HTMLIonCardElement | null>(null);
const animation = useRef<Animation | null>(null);
useEffect(() => {
if (animation.current === null) {
animation.current = createAnimation()
.addElement(cardEl.current!)
.duration(1500)
.iterations(Infinity)
.direction('alternate')
.fromTo('background', 'blue', 'var(--background)');
}
}, [cardEl]);
const play = () => {
animation.current?.play();
};
const pause = () => {
animation.current?.pause();
};
const stop = () => {
animation.current?.stop();
};
return (
<>
<IonCard ref={cardEl}>
<IonCardContent>Card</IonCardContent>
</IonCard>
<IonButton onClick={play}>Play</IonButton>
<IonButton onClick={pause}>Pause</IonButton>
<IonButton onClick={stop}>Stop</IonButton>
</>
);
}
export default Example;
src/main.css
ion-card {
color: white;
opacity: 0.5;
background: blue;
margin: 10px;
--background: red;
}
@media (prefers-color-scheme: dark) {
ion-card {
--background: green;
}
}
Vue
<template>
<ion-card ref="cardEl">
<ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button @click="play()">Play</ion-button>
<ion-button @click="pause()">Pause</ion-button>
<ion-button @click="stop()">Stop</ion-button>
</template>
<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';
const cardEl = ref(null);
let animation: Animation;
onMounted(() => {
animation = createAnimation()
.addElement(cardEl.value.$el)
.duration(1500)
.iterations(Infinity)
.direction('alternate')
.fromTo('background', 'blue', 'var(--background)');
});
const play = () => animation.play();
const pause = () => animation.pause();
const stop = () => animation.stop();
</script>
<style scoped>
ion-card {
color: white;
opacity: 0.5;
background: blue;
margin: 10px;
--background: red;
}
@media (prefers-color-scheme: dark) {
ion-card {
--background: green;
}
}
</style>
Overriding Ionic Component Animations (Ionic 컴포넌트 애니메이션 덮어쓰기)
일부 Ionic 컴포넌트는 개발자가 사용자 지정 애니메이션을 제공할 수 있게 해줍니다. 모든 애니메이션은 컴포넌트의 속성으로 제공되거나 전역 config를 통해 설정됩니다.
Modals (모달)
JavaScript
<ion-header>
<ion-toolbar>
<ion-title>Page</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<ion-button id="modal-trigger">Present Modal</ion-button>
<ion-modal trigger="modal-trigger">
<ion-header>
<ion-toolbar>
<ion-title>Modal</ion-title>
<ion-buttons slot="end">
<ion-button onclick="closeModal()">Close</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding"> Modal Content </ion-content>
</ion-modal>
</ion-content>
<script>
const modal = document.querySelector('ion-modal');
var closeModal = () => {
modal.dismiss();
};
const enterAnimation = (baseEl) => {
const root = baseEl.shadowRoot;
const backdropAnimation = createAnimation()
.addElement(root.querySelector('ion-backdrop'))
.fromTo('opacity', '0.01', 'var(--backdrop-opacity)');
const wrapperAnimation = createAnimation()
.addElement(root.querySelector('.modal-wrapper'))
.keyframes([
{ offset: 0, opacity: '0', transform: 'scale(0)' },
{ offset: 1, opacity: '0.99', transform: 'scale(1)' },
]);
return createAnimation()
.addElement(baseEl)
.easing('ease-out')
.duration(500)
.addAnimation([backdropAnimation, wrapperAnimation]);
};
const leaveAnimation = (baseEl) => {
return enterAnimation(baseEl).direction('reverse');
};
modal.enterAnimation = enterAnimation;
modal.leaveAnimation = leaveAnimation;
</script>
Angular
src/app/example.component.html
<ion-header>
<ion-toolbar>
<ion-title>Page</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<ion-button id="modal-trigger">Present Modal</ion-button>
<ion-modal trigger="modal-trigger" #modal>
<ng-template>
<ion-header>
<ion-toolbar>
<ion-title>Modal</ion-title>
<ion-buttons slot="end">
<ion-button (click)="closeModal()">Close</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding"> Modal Content </ion-content>
</ng-template>
</ion-modal>
</ion-content>
src/app/example.component.ts
import { Component, ViewChild } from '@angular/core';
import { IonButton, IonButtons, IonContent, IonHeader, IonModal, IonTitle, IonToolbar } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';
@Component({
selector: 'app-example',
templateUrl: 'example.component.html',
styleUrls: ['example.component.css'],
imports: [IonButton, IonButtons, IonContent, IonHeader, IonModal, IonTitle, IonToolbar],
})
export class ExampleComponent {
@ViewChild('modal', { static: true }) modal!: IonModal;
constructor(private animationCtrl: AnimationController) {}
ngOnInit() {
const enterAnimation = (baseEl: HTMLElement) => {
const root = baseEl.shadowRoot;
const backdropElement = root?.querySelector('ion-backdrop');
const wrapperElement = root?.querySelector('.modal-wrapper');
const backdropAnimation = this.animationCtrl
.create()
.addElement(backdropElement || baseEl)
.fromTo('opacity', '0.01', 'var(--backdrop-opacity)');
const wrapperAnimation = this.animationCtrl.create();
if (wrapperElement) {
wrapperAnimation.addElement(wrapperElement).keyframes([
{ offset: 0, opacity: '0', transform: 'scale(0)' },
{ offset: 1, opacity: '0.99', transform: 'scale(1)' },
]);
}
return this.animationCtrl
.create()
.addElement(baseEl)
.easing('ease-out')
.duration(500)
.addAnimation([backdropAnimation, wrapperAnimation]);
};
const leaveAnimation = (baseEl: HTMLElement) => {
return enterAnimation(baseEl).direction('reverse');
};
this.modal.enterAnimation = enterAnimation;
this.modal.leaveAnimation = leaveAnimation;
}
closeModal() {
this.modal.dismiss();
}
}
React
import React, { useRef } from 'react';
import {
IonButton,
IonButtons,
IonContent,
IonHeader,
IonModal,
IonToolbar,
IonTitle,
createAnimation,
} from '@ionic/react';
function Example() {
const modalEl = useRef<HTMLIonModalElement>(null);
const enterAnimation = (baseEl: HTMLElement) => {
const root = baseEl.shadowRoot!;
const backdropAnimation = createAnimation()
.addElement(root.querySelector('ion-backdrop')!)
.fromTo('opacity', '0.01', 'var(--backdrop-opacity)');
const wrapperAnimation = createAnimation()
.addElement(root.querySelector('.modal-wrapper')!)
.keyframes([
{ offset: 0, opacity: '0', transform: 'scale(0)' },
{ offset: 1, opacity: '0.99', transform: 'scale(1)' },
]);
return createAnimation()
.addElement(baseEl)
.easing('ease-out')
.duration(500)
.addAnimation([backdropAnimation, wrapperAnimation]);
};
const leaveAnimation = (baseEl: HTMLElement) => {
return enterAnimation(baseEl).direction('reverse');
};
const closeModal = () => {
modalEl.current?.dismiss();
};
return (
<>
<IonHeader>
<IonToolbar>
<IonTitle>Page</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding">
<IonButton id="modal-trigger">Present Modal</IonButton>
<IonModal trigger="modal-trigger" ref={modalEl} enterAnimation={enterAnimation} leaveAnimation={leaveAnimation}>
<IonHeader>
<IonToolbar>
<IonTitle>Modal</IonTitle>
<IonButtons slot="end">
<IonButton onClick={closeModal}>Close</IonButton>
</IonButtons>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding">Modal Content</IonContent>
</IonModal>
</IonContent>
</>
);
}
export default Example;
Vue
<template>
<ion-header>
<ion-toolbar>
<ion-title>Page</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<ion-button id="modal-trigger">Present Modal</ion-button>
<ion-modal trigger="modal-trigger" ref="modalEl" :enterAnimation="enterAnimation" :leaveAnimation="leaveAnimation">
<ion-header>
<ion-toolbar>
<ion-title>Modal</ion-title>
<ion-buttons slot="end">
<ion-button @click="closeModal()">Close</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding"> Modal Content </ion-content>
</ion-modal>
</ion-content>
</template>
<script setup lang="ts">
import {
IonButton,
IonButtons,
IonContent,
IonHeader,
IonModal,
IonToolbar,
IonTitle,
createAnimation,
} from '@ionic/vue';
import { ref } from 'vue';
const modalEl = ref(null);
const enterAnimation = (baseEl: HTMLElement) => {
const root = baseEl.shadowRoot;
const backdropAnimation = createAnimation()
.addElement(root!.querySelector('ion-backdrop')!)
.fromTo('opacity', '0.01', 'var(--backdrop-opacity)');
const wrapperAnimation = createAnimation()
.addElement(root!.querySelector('.modal-wrapper')!)
.keyframes([
{ offset: 0, opacity: '0', transform: 'scale(0)' },
{ offset: 1, opacity: '0.99', transform: 'scale(1)' },
]);
return createAnimation()
.addElement(baseEl)
.easing('ease-out')
.duration(500)
.addAnimation([backdropAnimation, wrapperAnimation]);
};
const leaveAnimation = (baseEl: HTMLElement) => {
return enterAnimation(baseEl).direction('reverse');
};
const closeModal = () => {
modalEl.value?.$el.dismiss();
};
</script>
Performance Considerations (성능 고려 사항)
CSS와 Web Animations는 보통 컴포지터(compositor) 스레드에서 처리됩니다. 이는 레이아웃, 페인팅, 스타일링, 그리고 JavaScript가 실행되는 메인 스레드와 다릅니다. 최적의 애니메이션 성능을 위해 컴포지터 스레드에서 처리할 수 있는 속성을 사용하는 것이 좋습니다.
height와 width 같은 속성을 애니메이션하면 추가적인 레이아웃과 페인트가 발생해 버벅임(jank)을 유발하고 성능을 떨어뜨릴 수 있습니다. 반면 transform과 opacity 같은 속성을 애니메이션하면 브라우저가 크게 최적화할 수 있어 보통 버벅임이 많이 발생하지 않습니다.
어떤 CSS 속성들이 레이아웃이나 페인트를 유발하는지에 대한 정보는 CSS Triggers를 참고하세요.
Debugging (디버깅)
Chrome에서 애니메이션을 디버깅하는 방법에 대해 Chrome DevTools를 사용해 애니메이션을 검사하는 좋은 블로그 글이 있습니다: https://developers.google.com/web/tools/chrome-devtools/inspect-styles/animations
또한 애니메이션에 고유한 식별자를 부여하는 것도 권장됩니다. 이 식별자들은 Chrome의 Animations 검사기에서 표시되며 디버깅을 더 쉽게 만들어 줍니다.
/**
* The animation for the .square element should
* show "my-animation-identifier" in Chrome DevTools.
*/
const animation = createAnimation('my-animation-identifier')
.addElement(document.querySelector('.square'))
.duration(1000)
.fromTo('opacity', '1', '0');
API
이 섹션에서는 Animation 클래스에서 사용 가능한 모든 메서드와 속성의 목록을 제공합니다.
Interfaces (인터페이스)
AnimationDirection
type AnimationDirection = 'normal' | 'reverse' | 'alternate' | 'alternate-reverse';
AnimationFill
type AnimationFill = 'auto' | 'none' | 'forwards' | 'backwards' | 'both';
AnimationBuilder
type AnimationBuilder = (baseEl: any, opts?: any) => Animation;
참고
opts는 사용자 지정 애니메이션에 특화된 추가 옵션입니다. 예를 들어 sheet modal의 enter 애니메이션에는 현재 breakpoint에 대한 정보가 포함됩니다.
AnimationCallbackOptions
interface AnimationCallbackOptions {
/**
* If true, the associated callback will only be fired once.
*/
oneTimeCallback: boolean;
}
AnimationPlayOptions
interface AnimationPlayOptions {
/**
* If true, the animation will play synchronously.
* This is the equivalent of running the animation
* with a duration of 0ms.
*/
sync: boolean;
}
Properties (속성)
| Name | Description |
|---|---|
childAnimations: Animation[] |
주어진 상위 애니메이션의 모든 자식 애니메이션. |
elements: HTMLElement[] |
애니메이션에 연결된 모든 요소. |
parentAnimation?: Animation |
주어진 애니메이션 객체의 상위 애니메이션. |
Methods (메서드)
| Name | Description |
|---|---|
addAnimation(animationToAdd: Animation | Animation[]): Animation |
하나 이상의 애니메이션을 묶어 하나의 상위 애니메이션이 제어하도록 합니다. |
addElement(el: Element | Element[] | Node | Node[] | NodeList): Animation |
애니메이션에 하나 이상의 요소를 추가합니다. |
afterAddClass(className: string | string[]): Animation |
애니메이션이 끝난 뒤 애니메이션의 모든 요소에 추가할 클래스 또는 클래스 배열을 지정합니다. |
afterAddRead(readFn: (): void): Animation |
애니메이션이 끝난 뒤 실행할 DOM 읽기 함수를 추가합니다. |
afterAddWrite(writeFn: (): void): Animation |
애니메이션이 끝난 뒤 실행할 DOM 쓰기 함수를 추가합니다. |
afterClearStyles(propertyNames: string[]): Animation |
애니메이션이 끝난 뒤 애니메이션의 모든 요소의 인라인 스타일에서 지울 속성 이름 배열을 추가합니다. |
afterRemoveClass(className: string | string[]): Animation |
애니메이션이 끝난 뒤 애니메이션의 모든 요소에서 제거할 클래스 또는 클래스 배열을 추가합니다. |
afterStyles(styles: { [property: string]: any }): Animation |
애니메이션이 끝난 뒤 애니메이션의 모든 요소에 적용할 스타일 객체를 추가합니다. |
beforeAddClass(className: string | string[]): Animation |
애니메이션이 시작되기 전에 애니메이션의 모든 요소에 추가할 클래스 또는 클래스 배열을 지정합니다. |
beforeAddRead(readFn: (): void): Animation |
애니메이션이 시작되기 전에 실행할 DOM 읽기 함수를 추가합니다. |
beforeAddWrite(writeFn: (): void): Animation |
애니메이션이 시작되기 전에 실행할 DOM 쓰기 함수를 추가합니다. |
beforeClearStyles(propertyNames: string[]): Animation |
애니메이션이 시작되기 전에 애니메이션의 모든 요소의 인라인 스타일에서 지울 속성 이름 배열을 추가합니다. |
beforeRemoveClass(className: string | string[]): Animation |
애니메이션이 시작되기 전에 애니메이션의 모든 요소에서 제거할 클래스 또는 클래스 배열을 추가합니다. |
beforeStyles(styles: { [property: string]: any }): Animation |
애니메이션이 시작되기 전에 애니메이션의 모든 요소에 적용할 스타일 객체를 추가합니다. |
direction(direction?: AnimationDirection): Animation |
애니메이션이 재생될 방향을 설정합니다. |
delay(delay?: number): Animation |
애니메이션 시작 지연 시간을 밀리초 단위로 설정합니다. |
destroy(clearStyleSheets?: boolean): Animation |
애니메이션을 파괴하고 모든 요소, 자식 애니메이션, 키프레임을 지웁니다. |
duration(duration?: number): Animation |
애니메이션의 지속 시간을 밀리초 단위로 설정합니다. |
easing(easing?: string): Animation |
애니메이션의 easing을 밀리초 단위로 설정합니다. 허용되는 easing 값 목록은 Easing Effects를 참고하세요. |
from(property: string, value: any): Animation |
애니메이션의 시작 스타일을 설정합니다. |
fromTo(property: string, fromValue: any, toValue: any): Animation |
애니메이션의 시작 및 끝 스타일을 설정합니다. |
fill(fill?: AnimationFill): Animation |
애니메이션 실행 전후에 요소에 스타일을 적용하는 방식을 설정합니다. |
iterations(iterations: number): Animation |
애니메이션 주기를 멈추기 전까지 재생할 횟수를 설정합니다. |
keyframes(keyframes: any[]): Animation |
애니메이션의 키프레임을 설정합니다. |
onFinish(callback: (didComplete: boolean, animation: Animation): void, opts?: AnimationCallbackOptions): Animation |
애니메이션이 끝날 때 실행할 콜백을 추가합니다. |
pause(): Animation |
애니메이션을 일시정지합니다. |
play(opts?: AnimationPlayOptions): Promise<void> |
애니메이션을 재생합니다. |
progressEnd(playTo?: 0 | 1, step: number, dur?: number): Animation |
애니메이션 탐색(seeking)을 중지합니다. |
progressStart(forceLinearEasing?: boolean, step?: number): Animation |
애니메이션 탐색을 시작합니다. |
progressStep(step: number): Animation |
애니메이션을 탐색합니다. |
stop(): Animation |
애니메이션을 중지하고 모든 요소를 초기 상태로 되돌립니다. |
to(property: string, value: any): Animation |
애니메이션의 끝 스타일을 설정합니다. |
더 알아보기 (Learn more)
이번에는 Ionic Animations의 설치, 기본·키프레임·그룹·연결·제스처 애니메이션 작성법, 그리고 Animation 클래스의 API까지 살펴봤어요. 다음으로는 Ionic Gestures 문서를 살펴보며 제스처 기반 상호작용을 더 깊게 다루어 보시길 권합니다.