CSS3 animation キーフレームアニメーション
今回は、CSS3のキーフレームアニメーションについて書きます。
キーフレームアニメーションを使うと、高度なアニメーションが作れます。
細かくアニメーションを設定できると言ったほうが、わかりやすいかな・・・
CSS3のアニメーションを初めて知る方は、こちらを先に見といたほうがいいです。
キーフレームアニメーションを使用するには、「animation」を使います。
「animation」のプロパティは、6つのあります。
- animation-name
- animation-duration
- animation-timing-function
- animation-delay
- animation-iteration-count
- animation-direction
簡単に、この6つを説明します。
1のanimation-nameは、キーフレームの名前です。
2のanimation-durationは、アニメーションにかかる時間(秒)です。
3のanimation-timing-functionは、変化のタイミングです。
4のanimation-delayは、何秒後にアニメーションをするか。
5のanimation-iteration-countは、アニメーションの繰り返し回数です。
6のanimation-directionは、アニメーションを交互に反転再生させるかどうかを指定します。
これらの書き方は、このように書きます。
animation-name: test; animation-duration: 1s; animation-timing-function: ease; animation-delay: -2s; animation-iteration-count: infinite; animation-direction:alternate;
また、こちらの6つのプロパティは、1行で指定できます。
animation: test 5s ease 1s infinite normal;
左から順にanimation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-directionとなっています。
間は、スペースで区切ります。
次は、キーフレームの設定です。
この設定で、アニメーションの詳細な動作を指定します。
このように書きます。
@keyframes test{ 0% {width: 300px; background: yellow; } 50% {width: 400px;background: orange; } 100% {width: 500px;background: red; } }
「@keyframes」の後の「 test」はキーフレームの名前です。上で書いた「animation-name」をここで使います。
0%や50%は、アニメーションの割合です。
つまり、アニメーションが0%の時、どんな形をしているか、アニメーションが50%の時にどんな形をしているか等を指定する感じです。
キーフレームの指定方法は以上で終わりです。
では、実際のプログラムを書きます。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>css3</title> <style> div{ width: 200px; height: 200px; background-color: blue; -webkit-animation: test 5s ease 1s infinite normal; } @-webkit-keyframes test{ 0% {width: 300px; background: yellow; } 50% {width: 400px;background: orange; } 100% {width: 500px;background: red; } } </style> </head> <body> <div id="nya"></div> </body> </html>
実行結果
アニメーションが0%の時
アニメーションが50%の時
上のプログラムは、幅が大きくなり、背景色も黄色→オレンジ→赤と変わっていきます。
さらに、無限にアニメーションを繰り返しようになっています。
ここで、補足ですが・・・
6のanimation-directionは、「normal」と「alternate」の2種類あります。
通常は、「normal」です。
「alternate」は、奇数回では普通方向の再生、偶数回では逆方向の再生となって、アニメーションサイクルを繰り返します。
5のanimation-iteration-count は、「infinite」と「数値による指定」の2種類の指定方法があります。
「infinite」は、無限にアニメーションを繰り返します。
数値をしていすると、その回数だけアニメーションします。
animation-iteration-count: 2;
以上で、終わります。
参考サイト
animation-CSS3リファレンス