LoginSignup
10
9

More than 5 years have passed since last update.

CSSのキーフレームアニメーションの開始位置をランダムにする方法

Posted at

CSSのキーフレームアニメーションの開始位置をランダムにする方法をご紹介します。

CSSアニメーションのプロパティには、

  • animation-name : アニメーションの名称
  • animation-duration : アニメーションの長さ
  • animation-timing-function : イージング
  • animation-delay : 何秒後にアニメーションを始めるか
  • animation-iteration-count : 繰り返し回数
  • animation-direction : アニメーションを逆再生するかどうか

といったものが用意されていますが、アニメーションを途中から再生するためのプロパティはありません。ですので、読み込むたびに毎回ランダムな再生位置でアニメーションを再生させたいという場合にどうすればよいか?

実は、"animation-delay"には負の値を設定することが出来ます。

"animation-iteration-count"を"infinite"にして、アニメーションを無限繰り返し状態にしている時に、"animation-delay"に負の値を設定すると、アニメーションの終わりから逆上った時点からスタートされます。

例えば"animation-duration:20s"、"animation-delay:-5s"のようにすると、15秒後の位置からスタートされます。

後は、Javascriptで、ランダムな秒数のアニメーションを読み込み時に設定してあげれば、開始位置がランダムなアニメーションが出来るというわけです。

以下は、背景色がじわじわと変わるCSSアニメーションのデモです。四角をクリックするたびに違う色からスタートするのがわかります。

%html
  %body
    #box
@import compass

#box
  width: 200px
  height: 200px

@-webkit-keyframes anime1
  0%
    background-color: #DBAD00
  10%
    background-color: #CC6700
  20%
    background-color: #CC2F00
  30%
    background-color: #CC0090
  40%
    background-color: #6A00CC
  50%
    background-color: #000ECC
  60%
    background-color: #00A1CC
  70%
    background-color: #00CC75
  80%
    background-color: #00CC02
  90%
    background-color: #A8CC00
  100%
    background-color: #DBAD00

$ ->
  $('#box').css
    'animation':'anime1 10s ease -'+Math.random()*10+'s infinite'

 $(document).on 'click','#box',->
    $('#box').remove()
    $('body').append '<div id="box"></div>'
    $('#box').css 'animation':'anime1 10s ease -'+Math.random()*10+'s infinite'

See the Pen YPwGoa by TAKAYASU SAGAWA (@shagggy) on CodePen.

10
9
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
10
9