前端每日實戰:134# 視頻演示如何用 CSS 和 GSAP 創做一個樹枝發芽的 loader

圖片描述

效果預覽

按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。javascript

https://codepen.io/comehope/pen/LJmpXZcss

可交互視頻

此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。html

請用 chrome, safari, edge 打開觀看。前端

https://scrimba.com/p/pEgDAM/cdD8WHVjava

源代碼下載

每日前端實戰系列的所有源代碼請從 github 下載:git

https://github.com/comehope/front-end-daily-challengesgithub

代碼解讀

定義 dom,容器包含 2 個元素,branch 表明枝,leaves 表明葉,葉有 6 個子元素,表明 6 個葉片:ajax

<figure class="sapling">
    <div class="branch"></div>
    <div class="leaves">
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
    </div>
</figure>

居中顯示:chrome

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: black;
}

定義容器尺寸,並設置子元素水平居中:dom

.sapling {
    position: relative;
    width: 5em;
    height: 17.5em;
    font-size: 10px;
    display: flex;
    justify-content: center;
}

畫出樹枝:

.branch {
    position: absolute;
    width: 0.2em;
    height: inherit;
    border-radius: 25%;
    background: burlywood;
}

定義樹葉容器,設置爲葉片在垂直方向均勻分佈,而且從下到上排列:

.leaves {
    position: absolute;
    width: inherit;
    height: 15em;
    top: 1em;
    display: flex;
    flex-direction: column-reverse;
}

設置葉片的尺寸和和背景顏色:

.leaves span {
    width: 2.5em;
    height: 2.5em;
    background-color: limegreen;
}

設置左右葉片的各自樣式:

.leaves span:nth-child(odd) {
    border-bottom-left-radius: 3em;
    border-top-right-radius: 3em;
    transform-origin: right bottom;
    align-self: flex-start;
}

.leaves span:nth-child(even) {
    border-bottom-right-radius: 3em;
    border-top-left-radius: 3em;
    transform-origin: left bottom;
    align-self: flex-end;
}

至此,靜態效果繪製完成,接下來開始寫動畫腳本。
引入 GSAP 庫:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js"></script>

聲明一個時間線對象:

let animation = new TimelineMax();

增長樹枝的入場動畫效果,併爲這個動畫設置一個標籤 branch

animation.from('.branch', 4, {scaleY: 0, ease: Power1.easeOut}, 'branch');

增長樹葉的入場動畫效果,它的參數中有 3 個 0.5,從左到右的含義分別是動畫時長、多個葉片動畫的間隔時長、相對 branch 標籤動畫的延遲時間:

animation.from('.branch', 4, {scaleY: 0, ease: Power1.easeOut}, 'branch')
    .staggerFrom('.leaves span', 0.5, {scale: 0, ease: Power1.easeOut}, 0.5, 0.5, 'branch');

增長葉片變黃的動畫效果:

animation.from('.branch', 4, {scaleY: 0, ease: Power1.easeOut}, 'branch')
    .staggerFrom('.leaves span', 0.5, {scale: 0, ease: Power1.easeOut}, 0.5, 0.5, 'branch')
    .to(['.branch', '.leaves span'], 3, {backgroundColor: 'yellow'});

增長淡出效果:

animation.from('.branch', 4, {scaleY: 0, ease: Power1.easeOut}, 'branch')
    .staggerFrom('.leaves span', 0.5, {scale: 0, ease: Power1.easeOut}, 0.5, 0.5, 'branch')
    .to(['.branch', '.leaves span'], 3, {backgroundColor: 'yellow'})
    .to(['.branch', '.leaves span'], 1, {autoAlpha: 0});

修改聲明時間線的代碼,使動畫重複播放:

let animation = new TimelineMax({repeat: -1, repeatDelay: 0.5});

大功告成!

相關文章
相關標籤/搜索