前端每日實戰:70# 視頻演示如何用純 CSS 創做一隻徘徊的果凍怪獸

圖片描述

效果預覽

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

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

可交互視頻

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

請用 chrome, safari, edge 打開觀看。git

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

源代碼下載

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

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

代碼解讀

定義 dom,容器中包含 2 個元素,分別表明怪獸的身體和眼睛:動畫

<div class="monster">
    <span class="body"></span>
    <span class="eyes"></span>
</div>

設置背景色:spa

body {
    margin: 0;
    height: 100vh;
    background-color: black;
}

設置前景色:code

.monster {
    width: 100vw;
    height: 50vh;
    background-color: lightcyan;
}

畫出怪獸的身體:

.monster {
    position: relative;
}

.body {
    position: absolute;
    width: 32vmin;
    height: 32vmin;
    background-color: teal;
    border-radius: 43% 40% 43% 40%;
    bottom: calc(-1 * 32vmin / 2 - 4vmin);
}

定義怪獸眼睛所在的容器:

.eyes {
    width: 24vmin;
    height: 5vmin;
    position: absolute;
    bottom: 2vmin;
    left: calc(32vmin - 24vmin - 2vmin);
}

用僞元素畫出怪獸的眼睛:

.eyes::before,
.eyes::after {
    content: '';
    position: absolute;
    width: 5vmin;
    height: 5vmin;
    border: 1.25vmin solid white;
    box-sizing: border-box;
    border-radius: 50%;
}

.eyes::before {
    left: 4vmin;
}

.eyes::after {
    right: 4vmin;
}

爲怪獸定義輕輕跳起的動畫,結合後面的動畫效果,讓它具備果凍的彈性:

.body {
    animation:
        bounce 1s infinite alternate;
}

@keyframes bounce {
    to {
        bottom: calc(-1 * 32vmin / 2 - 2vmin);
    }
}

讓怪獸的身體轉動起來:

@keyframes wave {
    to {
        transform: rotate(360deg);
    }
}

讓怪獸徘徊行走:

.monster {
    overflow: hidden;
}

.body {
    left: -2vmin;
    animation:
        wander 5s linear infinite alternate,
        wave 3s linear infinite,
        bounce 1s infinite alternate;
}

.eyes {
    animation: wander 5s linear infinite alternate;
}

@keyframes wander {
    to {
        left: calc(100% - 32vmin + 2vmin);
    }
}

最後,讓怪獸的眼睛眨一眨:

.eyes::before,
.eyes::after {
    animation: blink 3s infinite linear;
}

@keyframes blink {
    4%, 10%, 34%, 40% {
        transform: scaleY(1);
    }

    7%, 37% {
        transform: scaleY(0);
    }
}

大功告成!

相關文章
相關標籤/搜索