LoginSignup
4
5

More than 5 years have passed since last update.

CSSパラパラアニメを複数background-imageで作る

Last updated at Posted at 2016-06-04

はじめに

CSSでパラパラアニメを作ろうと思い立ちまして、そこでググって作り方調べたりしますと、だいたいCSSスプライトを使った方法に行き当たります。こういうのですね。

CSSスプライトとstepsを使ってアニメーション画像を作ろう

でも、めんどくさいんですよ。CSSスプライト。ひとコマ修正が入っても全体つなぎ直しですよ。つなぐときに1ピクセルずれてたらまたやりなおしですよ。うがー!
ふつーのセル画のように、ひとコマ=1ファイルなら、作成も修正もやりやすいじゃないですか。デザイナーさんから素材もらってすぐ実装できるじゃないですか。フォトショ開いてちまちまずらしたり、あーだこーだパラメータいじってgrunt使ってつないだりする必要ないじゃないですか。
というわけで作ってみます。

実装

素材を用意します。
ぴぽや倉庫さんからお借りいたしました。ありがとうございます。

スクリーンショット 2016-06-04 15.06.17.png

(配布されている素材は一枚画像なので、同サイズで切り分けています。なんか本末転倒ですが)

箱としてはこんな感じ。

<div class="frame">
  <div id="cell" class="cell"></div>
</div>

この <div id="cell"></div> 内に画像素材を縦に並べる要領で、複数配置します。animation-timing-functionsteps() を指定して、CSSアニメーションで縦にスライドさせていけば、アニメーションになるわけですね。その辺の理屈は上のリンク先と一緒です。

そしてできたCSSは以下のとおり。

.frame {
  width: 240px;
  height: 240px;
  overflow: hidden;
  cursor: pointer;
}
.cell {
  width: 100%;
  height: 2000%;
  background-color: transparent;
  background-repeat: no-repeat;
  background-image: url(01.png),url(02.png),url(03.png),url(04.png),url(05.png),url(06.png),url(07.png),url(08.png),url(09.png),url(10.png),url(11.png),url(12.png),url(13.png),url(14.png),url(15.png),url(16.png),url(17.png),url(18.png),url(19.png),url(20.png);
  background-position: 0 0, 0 240px, 0 480px, 0 720px, 0 960px, 0 1200px, 0 1440px, 0 1680px, 0 1920px, 0 2160px, 0 2400px, 0 2640px, 0 2880px, 0 3120px, 0 3360px, 0 3600px, 0 3840px, 0 4080px, 0 4320px, 0 4560px;
  animation-name: parapara;
  animation-duration: 1s;
  animation-iteration-count: 1;
  animation-timing-function: steps(20);
}
@keyframes parapara {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(-100%);
  }
}

159wup.gif

動きましたよー!

stylusで作成

上のCSSをベタで書くのは面倒すぎますので、実際はstylusを使って書いています。
セルのサイズと画像ファイルを配列で指定すれば background-image background-position が自動的に埋まるという寸法です。

w = 240
h = 240
// 画像ファイルを配列(スペース区切り)で指定
cells = '01.png' '02.png' ...

bgis = ()
for i in cells
  push(bgis, url(i))

bgps = ()
for p in 0...length(cells)
  push(bgps, unquote('0 '+(p * h)+'px'))

.wrap
  margin 20px

.frame
  width w px
  height h px
  overflow hidden
  cursor pointer

.cell
  width 100%
  height (100 * length(cells))%
  background-color transparent
  background-repeat no-repeat
  background-image unquote(join(',', bgis))
  background-position unquote(join(',', bgps))
  animation-name parapara
  animation-duration 1s
  animation-iteration-count 1
  animation-timing-function steps(length(cells))

@keyframes parapara
  0%
    transform translateY(0)
  100%
    transform translateY(-100%)

イテレーション万歳。

4
5
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
4
5