アイキャッチ画像

Astroでビュートランジション(ページ切り替え時のアニメーション)を実装する

本記事ではAstroでViewTransitions(ビュートランジション)を実装します。

ビュートランジションとはこういうものです。(このサイトにも実装されています。)

ページ切り替え時にふわっとフェードしながら切り替わります。

Astroならたった2行のコードで実装できますよ。

ビュートランジションの実装方法

import { ViewTransitions } from 'astro:transitions';をヘッドマターに、
<ViewTransitions /><head>タグ内に設置します。

これを対象となる全ページに配置します。

index.astro
---
import { ViewTransitions } from 'astro:transitions'; //⇐コレを追加
---
<html lang="ja">
  <head>
    <title>私のホームページ</title>
    <ViewTransitions /> //⇐コレを追加
  </head>
  <body>
    <h1>私のウェブサイトへようこそ!</h1>
  </body>
</html>

サイト全体に適応する場合はレイアウトファイルに記載するのが現実的だと思います。

私の場合は以下の様にレイアウトファイルに記載しました。

Layout.astro
---
//リセットCSS
import "../css/style.scss";

import { ViewTransitions } from "astro:transitions";

//ヘッダー読み込み
import Header from "../components/Header.astro";
import Footer from "../components/Footer.astro";
import GtmHead from "../components/GtmHead.astro";
import GtmBody from "../components/GtmBody.astro";
import StructuredData from "../components/StructuredData.astro";

import MenuScript from "../components/MenuScript.astro";

interface Props {
  title: string;
}

const siteUrl = "https://it-web.jp/";
const description = "江南市を拠点にホームページ制作のお困りごとを解決します。コーポレートサイトやランディングページの制作から運用まで、モダンな技術を活用した質の高いウェブサイトをご提供。お客様と一緒に、唯一無二のホームページを創り上げます。";

const { title } = Astro.props;
---

<!doctype html>
<html lang="ja">
  <head>
    <!-- Google Tag Manager -->
    <GtmHead />
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- サイトの説明 -->
    <meta name="description" content={description} />
    <!-- Favicon -->
    <link rel="icon" href="/favicon.png" sizes="any" />
    <!-- OGP -->
    <meta property="og:title" content={title} />
    <meta property="og:description" content={description} />
    <meta property="og:type" content="website" />
    <meta property="og:url" content={siteUrl} />
    <meta property="og:image" content={`${siteUrl}ogp.png`} />

    <!-- X(Twitter) OGP -->
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:image" content={`${siteUrl}ogp.png`} />

    <!-- 構造化データ -->
    <StructuredData />
    <!-- 検索結果表示可、クロール可 -->
    <meta name="robots" content="index, follow" />
    <!-- サイトマップを送る -->
    <link rel="sitemap" href="/sitemap-index.xml" />
    <ViewTransitions />
    <title>{title}</title>
    <MenuScript />
  </head>
  <body>
    <!-- Google Tag Manager (noscript) -->
    <GtmBody />
    <Header />
    <slot />
    <Footer />
  </body>
</html>

ビュートランジションのオプション

切り替えアニメーションはデフォルトではfadeとなっていますが、その他にもslidenoneなども提供されています。

各アニメーションの調整も可能なので、詳しくは公式ドキュメンを参照下さい。

最後に

本記事ではAstroでビュートランジションを設定する方法をまとめました。

簡単なコードの記載だけで切替時のアニメーションが設定できるのは便利ですよね。

当サイトで使ってみるといい感じだったので、しばらくはありのままにしておこうと思います。

もしこの記事が役に立ったと感じていただけた方は、ぜひX(旧Twitter)やブログなどでシェアしていただけると嬉しいです。

最後までお読みいただき、ありがとうございました!

他にもこんな記事が読まれています

Webサイト制作に関する
ご相談はお気軽に。