1. 程式人生 > >如何用純 CSS 創作一隻徘徊的果凍怪獸

如何用純 CSS 創作一隻徘徊的果凍怪獸

效果預覽

線上演示

按下右側的“點選預覽”按鈕可以在當前頁面預覽,點選連結可以全屏預覽。


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


可互動視訊


此視訊是可以互動的,你可以隨時暫停視訊,編輯視訊中的程式碼。


請用 chrome, safari, edge 開啟觀看。


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


原始碼下載


本地下載

每日前端實戰系列的全部原始碼請從 github 下載:


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


程式碼解讀


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

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

設定背景色:

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

設定前景色:

.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);
    }
}

大功告成!

原文地址:https://segmentfault.com/a/1190000015484852