[CSS100] Day 09 Weather
Cathy P

Weather Demo

See the Pen 100DaysCss #08 by Cathy (@smile25896) on CodePen.

這次的題目不難,大致上可以分成兩個重點Sass的語法學習和雨滴動畫。
雨滴的造型只要用到偽元素就能簡單達成,而雨滴降落的動畫對於我來說,更像一個數學習題,要調整雨滴降落的時間與延遲的速度,才能讓雨滴降落顯得自然。

學習重點

  1. Sass for迴圈
  2. Sass @extend
  3. 雨滴製作
  4. 雨滴落下的動畫

scss for迴圈

Sass裡有迴圈的用法,如下:

1
2
3
4
5
6
7
@for $i from 1 through 10 {
.drop-big-#{$i} {
left: 40 * $i + px;
animation-delay: ( random(25)/10 ) + s;
animation-duration: ( random(10)/20+0.6 ) + s;
}
}

scss @extend

Sass裡也有繼承的用法

1
2
3
4
5
6
7
8
9
10
11
12
.circle {
width: 10px;
height: 10px;
border-radius: 50%;
background: red;
}

.circle-big {
@extend .square
width: 30px;
height: 30px;
}

轉成css會變成:

1
2
3
4
5
6
7
8
9
10
11
.circle, .circle-big {
width: 10px;
height: 10px;
border-radius: 50%;
background: red;
}

.circle-big {
width: 30px;
height: 30px;
}

scss甚至可以寫成以下,也有同樣的效果

1
2
3
4
5
6
7
8
9
10
11
12
.circle {
width: 10px;
height: 10px;
border-radius: 50%;
background: red;

&-big {
@extend .square
width: 30px;
height: 30px;
}
}

雨滴製作

雨滴是由一個圓形+三角形(before偽元素)組合成的,
原本想直接讓整個雨滴透過transform: rotate()轉向。
但因為雨滴落到地上時,要有一個扁掉的效果,扁掉的效果我透過transform: scale(1.5, 0.5)達成,
但若整個雨滴透過transform: rotate()轉過方向,則扁掉的地方不會水平。
因此,我只旋轉了三角形的部分並調整位置,達到斜斜的雨滴效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$drop-color: #7FC1F9;

.drop{
position: absolute;
top: -10px;
left: 300px;
width: 10px;
height: 10px;
border-radius: 50%;
background: $drop-color;
animation: down 1.2s linear 0s infinite;

&:before{
content: '';
display: block;
position: relative;
top: -5px;
left: 2px;
width: 0;
height: 0;
border-style: solid;
border-width: 0 5px 10px 5px;
border-color: transparent transparent $drop-color transparent;
transform: rotate(20deg);
}
}

雨滴落下的動畫

讓雨滴落下的關鍵影格其實不難,
可以拆解成 1.雨滴往左下方移動(0%~90%)2.在最低點時扁掉(90%~100%) 這兩個部分。

1
2
3
4
5
6
7
8
9
10
11
@keyframes down {
0% {
transform: rotate(0deg) translate(0, 0);
}
90% {
transform: rotate(0deg) translate(-80px, 314px) scale(1, 1);
}
100% {
transform: rotate(0deg) translate(-80px, 314px) scale(1.5, 0.5);
}
}

要讓雨滴落的自然,
要靠animation-delayanimation-duration去調整,
讓雨掉落的時間與速率都稍微錯開。
另外一個細節就是,近的(大的)雨滴要落得比較快,遠的(小的)雨滴要落得比較慢才會自然。

1
2
3
4
5
6
@for $i from 1 through 10 {
.drop-big-#{$i} {
animation-delay: ( random(25)/10 ) + s;
animation-duration: ( random(10)/20+0.6 ) + s;
}
}