#44 写真が右端から左へループするアニメーション【ぴよぴよコーダーの開発日記】
まずはデモ
Swiper.js使おうかと迷ったけど、CSSでできるのでは?と思ったらCSSだけで作っているページがありました。
ループしたい画像を横に2枚ならべて、translateXで位置を、1枚目は右端である100%から0にずらす。2枚目は200%から0にずらす。その際に1枚目の移動開始時間を2枚目の半分にする。
HTMLは下記。
<div class="loop_wrap">
<img src="./img/pc_img-loop.png"><img src="./img/pc_img-loop.png">
</div>
CSSは、
.loop_wrap {
display: flex;
width: 100vw;
height: calc(100vw * .07);
overflow: hidden;
}
.loop_wrap img {
width: auto;
min-width: 100vw;
height: 100%;
}
@keyframes loop {
0% {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
@keyframes loop2 {
0% {
transform: translateX(0);
}
to {
transform: translateX(-200%);
}
}
.loop_wrap img:first-child {
animation: loop 50s -25s linear infinite;
}
.loop_wrap img:last-child {
animation: loop2 50s linear infinite;
}
参考:写真が画面の端から端へ流れる無限ループするアニメーション
上記のデモ
つまづいた所
ソースにある画像の高さ height: calc(100vw * .07); の.07というのは、画像1枚のサイズが、1708px * 120px なので、計算的には、120 / 1708 = 0.07という求め方です。heightはwidthの100vwに対して、0.07の比率の高さですよってこと。
あとデザイナーさんが用意してくれたデザインカンプを見ると、PCの時とSPの時では、表示領域が違っていた(SPの時は4枚だけ表示されている)ので、SP用の画像も作成。CSSは下記のような感じ。
@media screen and (max-width: 768px) {
.loop_wrap {
height: calc(100vw * .174);
}
.loop_wrap img:first-child {
animation: loop 20s -10s linear infinite;
}
.loop_wrap img:last-child {
animation: loop2 20s linear infinite;
}
}
上の式に当てはめると、SPの画像サイズがwidthが684pxでheightが120pxなので、120/684で0.174の比率の高さとなる。
画像のwidthがPCの時に比べると、684 / 1708 = 0.4と、40%ほどの長さとなったので、移動スピードをPCに合わせるには、速さも 50 * 0.4 = 20で20sに変更、それに伴い1枚目の移動開始時間を、その半分の10sに変更。
なかなか考えさせられたなぁ。。
この記事が気に入ったらサポートをしてみませんか?