按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。javascript
https://codepen.io/comehope/pen/Yjomydcss
此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。html
請用 chrome, safari, edge 打開觀看。前端
https://scrimba.com/p/pEgDAM/cydZrfrjava
每日前端實戰系列的所有源代碼請從 github 下載:git
https://github.com/comehope/front-end-daily-challengesgithub
定義 dom,容器中包含 3 個子元素,每一個子元素表明一個圓:chrome
<div class="circles"> <span></span> <span></span> <span></span> </div>
居中顯示:app
body { margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background-color: black; }
定義容器尺寸:dom
.circles { width: 60vmin; height: 60vmin; }
畫出容器中的1個圓:
.circles { position: relative; } .circles span { position: absolute; box-sizing: border-box; width: 50%; height: 50%; background-color: white; border-radius: 50%; left: 25%; }
定義變量,畫出多個圓,每一個圓圍繞着第 1 個圓的底部中點旋轉,圍成一個更大的圓形:
.circles { --particles: 3; } .circles span { transform-origin: bottom center; --deg: calc(360deg / var(--particles) * (var(--n) - 1)); transform: rotate(var(--deg)); } .circles span:nth-child(1) { --n: 1; } .circles span:nth-child(2) { --n: 2; } .circles span:nth-child(3) { --n: 3; }
爲子元素增長動畫效果:
.circles span { animation: rotating 5s ease-in-out infinite; } @keyframes rotating { 0% { transform: rotate(0); } 50% { transform: rotate(var(--deg)) translateY(0); } 100% { transform: rotate(var(--deg)) translateY(100%) scale(2); } }
設置子元素混色模式,使子元素間交疊的部分顯示成黑色:
.circles span { mix-blend-mode: difference; }
爲容器增長動畫效果,抵銷子元素放大,使動畫流暢銜接:
.circles { animation: zoom 5s linear infinite; } @keyframes zoom { to { transform: scale(0.5) translateY(-50%); } }
接下來用 d3 批量處理 dom 元素和 css 變量。
引入 d3 庫:
<script src="https://d3js.org/d3.v5.min.js"></script>
用 d3 爲表示圓數量的變量賦值:
const COUNT_OF_PARTICLES = 30; d3.select('.circles') .style('--particles', COUNT_OF_PARTICLES)
用 d3 生成 dom 元素:
d3.select('.circles') .style('--particles', COUNT_OF_PARTICLES) .selectAll('span') .data(d3.range(COUNT_OF_PARTICLES)) .enter() .append('span');
用 d3 爲表示子元素下標的變量賦值:
d3.select('.circles') .style('--particles', COUNT_OF_PARTICLES) .selectAll('span') .data(d3.range(COUNT_OF_PARTICLES)) .enter() .append('span') .style('--n', (d) => d + 1);
刪除掉 html 文件中的相關 dom 元素和 css 文件中相關的 css 變量。
最後,把圓的數量調整爲 30 個:
const COUNT_OF_PARTICLES = 30;
大功告成!