Animate.cssは、CSSベースのアニメーション効果を簡単に実装できる人気のライブラリです。Velocity.jsなどのJavaScriptアニメーションライブラリとは異なり、CSSクラスの付与だけで動作します。
インストールと準備
パッケージマネージャーでインストールします。
npm install animate.css
Vueコンポーネントで読み込みます。
import 'animate.css'
基本的な使用方法
テンプレート側でアニメーション対象の要素を用意します。
<template>
<div class="container">
<button @click="triggerAnimation">アニメーション実行</button>
<div ref="targetEl" class="box">対象要素</div>
</div>
</template>
メソッド内でクラスを動的に追加します。アニメーション終了後にクラスを削除することで、繰り返し実行可能にします。
<script>
export default {
methods: {
triggerAnimation() {
const element = this.$refs.targetEl
const animationClass = 'animate__animated animate__bounceOutLeft'
element.classList.add(...animationClass.split(' '))
element.addEventListener('animationend', () => {
element.classList.remove(...animationClass.split(' '))
}, { once: true })
}
}
}
</script>
主要なアニメーション効果
フェード系
| クラス名 | 効果 |
|---|---|
animate__fadeIn | フェードイン |
animate__fadeInDown | 上からフェードイン |
animate__fadeInUp | 下からフェードイン |
animate__fadeOut | フェードアウト |
animate__fadeOutLeft | 左へフェードアウト |
バウンス系
| クラス名 | 効果 |
|---|---|
animate__bounceIn | バウンスで出現 |
animate__bounceOut | バウンスで消失 |
animate__bounceInUp | 下からバウンスイン |
ズーム系
| クラス名 | 効果 |
|---|---|
animate__zoomIn | ズームイン |
animate__zoomOut | ズームアウト |
animate__zoomInRight | 右からズームイン |
回転系
| クラス名 | 効果 |
|---|---|
animate__rotateIn | 回転しながら出現 |
animate__rotateOutDownLeft | 左下へ回転消失 |
animate__rotateInUpRight | 右上から回転イン |
フリップ系
| クラス名 | 効果 |
|---|---|
animate__flipInX | X軸フリップイン |
animate__flipOutY | Y軸フリップアウト |
アクセント系(繰り返し)
| クラス名 | 効果 |
|---|---|
animate__bounce | 跳ねる |
animate__pulse | 脉動 |
animate__shakeX | 左右に揺れる |
animate__tada | 拡縮しながら揺れる |
animate__swing | 振り子のように揺れる |
応用:コンポーネント化
再利用可能なアニメーションラッパーコンポーネントを作成します。
<template>
<transition
enter-active-class="animate__animated animate__fadeInUp"
leave-active-class="animate__animated animate__fadeOutDown"
>
<slot v-if="visible" />
</transition>
</template>
<script>
export default {
props: {
visible: Boolean
}
}
</script>
CSS変数でアニメーション速度を調整することも可能です。
:root {
--animate-duration: 0.5s;
--animate-delay: 0.2s;
}