LoginSignup
23
25

More than 5 years have passed since last update.

超簡単!SVGとCSSによるテキスト表示アニメーション

Posted at

初めに

自分のサイトのトップの文字を表示するアニメーションをSVGとCSSで実装したので書いていきます。

サンプル

アニメーションの原理はこちらを参考にしました。

とにかく試してみたいソースコード

HTML

<svg>
    <text x="0" y="50%">Hello</text>
</svg>

CSS

text {
    /* 色はお好みで */
    stroke: black;
    /* 文字の中身は塗りつぶさない */
    fill: none;
    /* 文字が大きい方がアニメーションが綺麗なので50pxを指定 */
    font-size: 50px;
    /* 100%だと最後まで表示されないので多めに設定する */
    stroke-dasharray: 150% 150%;
    /* 線が細いほうがアニメーションが綺麗なので0.5pxを指定 */
    stroke-width: 0.5px;
    -webkit-animation: stroke-anim 5s linear;
    animation: stroke-anim 5s linear;
}
@-webkit-keyframes stroke-anim {
  0% {
    /* 100%だと最後まで表示されないので多めに設定する */
    stroke-dashoffset: 150%;
  }
  100% {
    stroke-dashoffset: 0%;
  }
}

@keyframes stroke-anim {
  0% {
    /* 100%だと最後まで表示されないので多めに設定する */
    stroke-dashoffset: 150%;
  }
  100% {
    stroke-dashoffset: 0%;
  }
}

解説

試しみると下記のような「Hello」という文字がアニメーションで表示されます。

スクリーンショット 2017-08-16 16.29.15.png

文字の輪郭がアニメーションによって表示されるため文字の塗りつぶしをしたい場合は一工夫必要です。

塗りつぶし対応ソースコード

HTML

<svg>
    <text x="0" y="50%">Hello</text>
</svg>

CSS

text {
    /* 色はお好みで */
    stroke: black;
    /* 色はお好みで */
    fill: black;
    /* 文字が大きい方がアニメーションが綺麗なので50pxを指定 */
    font-size: 50px;
    /* 100%だと最後まで表示されないので多めに設定する */
    stroke-dasharray: 150% 150%;
    /* 線が細いほうがアニメーションが綺麗なので0.5pxを指定 */
    stroke-width: 0.5px;
    -webkit-animation: stroke-anim 5s linear;
    animation: stroke-anim 5s linear;
}
@-webkit-keyframes stroke-anim {
  0% {
    /* 100%だと最後まで表示されないので多めに設定する */
    stroke-dashoffset: 150%;
    fill:transparent;
  }
  50% {
    fill:transparent;
  }
  100% {
    stroke-dashoffset: 0%;
    fill:black;
  }
}

@keyframes stroke-anim {
  0% {
    /* 100%だと最後まで表示されないので多めに設定する */
    stroke-dashoffset: 150%;
    fill:transparent;
  }
  50% {
    fill:transparent;
  }
  100% {
    stroke-dashoffset: 0%;
    fill:black;
  }
}

解説

試しみると上記サンプルのように「Hello」の輪郭がアニメーションで表示された後、塗りつぶしアニメーションが開始され下記のように表示されます。

スクリーンショット 2017-08-16 17.15.07.png

終わりに

思ったより簡単に実装ができましたが、輪郭のアニメーションなので手書き風とはいかなかったです(`・ω・´)

23
25
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
23
25