LoginSignup
3
3

More than 5 years have passed since last update.

Nuxt.jsでロゴ等をアニメーションさせる Web Animations API編

Last updated at Posted at 2019-04-27

Nuxt.jsをチュートリアル通りに進めるとCSSアニメーションの
緑の三角形が動くアニメーションが表示される。
CSSアニメーションが苦手というだけの理由で
Web Animationsでアニメーションさせてみる

手順
1. CDNでpolyfillライブラリを読み込む
2. 画像追加してtemplate書く
3. javascriptで動かす


① Web AnimationsがまだPolyfillなのでライブラリをCDNで参照する

nuxt.config.js

  head: {
    title: pkg.name,
    // scriptにを追記
    script: [{src: "https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.1/web-animations-next.min.js"}],

②templateにアニメーションさせたい対象を追加

今回は画像(logo.png)をassetsに置いてLogo.vueをそのまま修正


<template>
  <img id="logo" src="~/assets/logo.png">
</template>

<style>
#logo {
  width: 120px;
}
</style>

③index.vueにアニメーションの処理を追加

ページ表示時にアニメーションを開始させるようにする
elementに直接アクセスするような処理はcreatedではなくmountedで行う。


<template>
  <section class="container">
    <div>
      <h1 id="title">animation</h1>
      <logo/>
    </div>
  </section>
</template>

<script>
import Logo from "~/components/Logo.vue";
// アニメーションの内容 繰り返し動き続けるパターン
const ANIMATIONS = {
  LOGO: {
    keyframes: [
      { opacity: 0.5, height: "119px", marginTop: "0px" },
      { opacity: 0.55, height: "119px", marginTop: "0px" },
      { opacity: 0.9, height: "110px", marginTop: "10px" },
      { opacity: 1, height: "105px", marginTop: "15px" }
    ],
    options: {
      duration: 2000,
      iterations: Infinity,
      direction: "alternate",
      fill: "forwards"
    }
  },
  LOGOTEXT: {
    keyframes: [{ opacity: 0.8 }, { opacity: 0.5 }],
    options: {
      duration: 1000,
      iterations: Infinity,
      direction: "alternate",
      fill: "forwards"
    }
  }
};

// 特定のDOMを動かす
const anim = (t, p) => {
  return new Animation(
    new KeyframeEffect(document.querySelector(t), p.keyframes, p.options),
    document.timeline
  ).play();
};

export default {
  /* 追記ここから */
  mounted() {
    this.$nextTick(() => {
      anim("#logo", ANIMATIONS.LOGO);
      anim("#title", ANIMATIONS.LOGOTEXT);
    });
  },
  /* 追記ここまで */
  components: {
    Logo
  }
};
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

#title {
  display: block;
  font-weight: 300;
  font-size: 30px;
  color: #35495e;
  letter-spacing: 1px;
}

</style>

とりあえず完成。
もっとNuxt.jsに寄り添った感じにしたい

gamen_test1.gif

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3