1. 程式人生 > >如何用純 CSS 和 D3 創作一隻扭動的蠕蟲

如何用純 CSS 和 D3 創作一隻扭動的蠕蟲

效果預覽

線上演示

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

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

可互動視訊

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

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

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

原始碼下載

本地下載

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


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


程式碼解讀


定義 dom,容器中包含 3 個元素,代表蠕蟲的 3 個體節:


<div class="worm">
<span></span>
<span></span>
<span></span>
</div>

居中顯示:


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

畫出蠕蟲最大的體節:


.worm {
display: flex;
align-items: center;
justify-content: center;
}

.worm span {
position: absolute;
width: 90vmin;
height: 90vmin;
background-color: hsl(336, 100%, 19%);
border-radius: 50%;
border: 3px solid;
border-color: hsl(336, 100%, 36%);
}


定義 css 變數:


.worm {
--particles: 3;
}

.worm span:nth-child(1) {
--n: 1;
}

.worm span:nth-child(2) {
--n: 2;
}

.worm span:nth-child(3) {
--n: 3;
}


用變數定義體節的尺寸,畫出其他體節:


.worm span {
--diameter: calc(100vmin - var(--n) * 90vmin / var(--particles));
width: var(--diameter);
height: var(--diameter);
}

用變數定義體節的顏色,使它們顯得有層次感:


.worm span {
background-color: hsl(336, 100%, calc((19 + var(--n) * 3) * 1%));
border-color: hsl(336, 100%, calc((36 + var(--n) * 1) * 1%));
box-shadow: 0 0 33px rgba(0, 0, 0, 0.3);
}

定義動畫效果:


.worm span {
animation: rotating 4s infinite cubic-bezier(0.6, -0.5, 0.3, 1.5);
}

@keyframes rotating {
from {
transform-origin: 0%;
}

to {
    transform: rotate(1turn);
    transform-origin: 0% 50%;
}

}


用變數設定動畫延時:


.worm span {
animation-delay: calc(1s - var(--n) * 100ms);
}

隱藏頁面外的內容:


body {
overflow: hidden;
}

接下來用 d3 批量處理 dom 元素。
引入 d3 庫:


<script src="https://d3js.org/d3.v5.min.js"></script>

用 d3 為 --particles 變數賦值:


const COUNT_OF_PARTICLES = 3;

d3.select('.worm')
.style('--particles', COUNT_OF_PARTICLES);


用 d3 建立 dom 元素:


d3.select('.worm')
.style('--particles', COUNT_OF_PARTICLES)
.selectAll('span')
.data(d3.range(COUNT_OF_PARTICLES))
.enter()
.append('span');

用 d3 為 dom 元素的 --n 屬性賦值:


d3.select('.worm')
.style('--particles', COUNT_OF_PARTICLES)
.selectAll('span')
.data(d3.range(COUNT_OF_PARTICLES))
.enter()
.append('span')
.style('--n', (d) => d + 1);

刪除掉 html 檔案中宣告 dom 元素的程式碼,刪除掉 css 檔案中宣告 --particles 和 --n 變數的程式碼。


最後,把 dom 元素數設定為 12 個:


const COUNT_OF_PARTICLES = 12;

大功告成!


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