LoginSignup
1
0

More than 3 years have passed since last update.

cssの@keyframesアニメーションでガタゴト進む車を実装する

Last updated at Posted at 2020-10-11

完成版デモ

See the Pen ガタゴト進む車 by kuma-onigiri (@kuma-onigiri) on CodePen.

実装イメージ

アニメーションは@keyframesを使います
1、車の画像を配置する
2、斜めに動くアニメーションをつける
3、上下にガタゴト動くアニメーションをつける

車を用意する

Illustratorで作った車をつかいます
car.png

ベースのHTMLとCSS

index.html
            <div class="move-animation">
                <div class="gata-gata-animation">
                    <img class="car" src="車の画像のパス">
                </div>
            </div>
main.css
.car {
    width: 75px; /* 車のサイズは適当に幅75pxくらい */
}

@keyframesは、1つの要素に複数のアニメーションをつけることはできないので、2段構えでつけています。
上下に揺れる用のgata-gata-animationクラスをつけた要素を、さらに<div>で囲って、動くアニメーション用のmove-animationクラスをつけてあげるのがポイントです。

斜めに動くアニメーションをつける

main.css
.move-animation {
    transform: translate(250px, 0px);

    animation: move 16s linear infinite;
}
@keyframes move {
    to {
        transform: translate(0px, 250px);
    }
}

初期位置はtranslateで右に250pxくらいずらした状態にしておきます。
そこから左下に動いていくアニメーションをつけます。時間は適当に16秒くらいにしてます。

上下にガタゴトうごくアニメーションをつける

main.css
.gata-gata-animation {
    animation: gata-goto .3s infinite;
}
@keyframes gata-goto {
    20% {
        transform: translateY(-2px);
        animation-timing-function: cubic-bezier(0.4, 0, 1, 1.3);
    }
    25% {
        transform: translateY(0px);
    }
    55% {
        transform: translateY(-1px);
        animation-timing-function: cubic-bezier(0.4, 0, 1, 1.3);
    }
    60% {
        transform: translateY(0px);
    }
}

transformで上下に2回動くのを作り、それをinfiniteで延々と繰り返しています。
ちょっとバウンドする感じにしたいのでanimation-timing-functioncubic-bezier(0.4, 0, 1, 1.3)にしています。

ここはブラウザの開発者ツールで調整できるのですが、
左の赤丸のところのマークをクリックするとベジエ曲線のグラフが出てくるので、ハンドルを動かして好きな動きにできます。
右の赤丸のところを上に盛り上がるようにすると、ぼよんって感じの動きになります。
bezier.png

おわり

アニメーションを2段構えにするのがポイントでした。
これを応用すれば、ぴょんぴょん動くアニメーションとかもできますね。

1
0
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
1
0