按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。javascript
https://codepen.io/comehope/pen/NBvrWLcss
此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。html
請用 chrome, safari, edge 打開觀看。前端
https://scrimba.com/p/pEgDAM/czD3PhMjava
每日前端實戰系列的所有源代碼請從 github 下載:git
https://github.com/comehope/front-end-daily-challengesgithub
定義 dom,容器中包含 1 個內含 5 個 <span>
的 <div>
:chrome
<div class="container"> <div class="hexagons"> <span></span> <span></span> <span></span> <span></span> <span></span> </div> </div>
居中顯示:app
body { margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background: radial-gradient(circle at center, gold, black); }
定義圓形的外層容器的尺寸:dom
.container { width: 20em; height: 20em; font-size: 20px; border-radius: 50%; }
在六邊形容器中畫出 1 個矩形:
.hexagons { width: inherit; height: inherit; display: flex; align-items: center; justify-content: center; } .hexagons span { position: absolute; width: calc(20em / 1.732); height: inherit; background-color: currentColor; }
用僞元素再建立 2 個相同大小的矩形,一塊兒組成一個六邊形:
.hexagons span:before, .hexagons span:after { content: ''; position: absolute; width: inherit; height: inherit; background-color: currentColor; } .hexagons span:before { transform: rotate(60deg); } .hexagons span:after { transform: rotate(-60deg); }
讓六邊形的顏色交錯呈現:
.hexagons span:nth-child(odd) { color: gold; } .hexagons span:nth-child(even) { color: #222; }
設置變量,讓六邊形逐漸縮小,小六邊形重疊在大六邊形的上面:
.hexagons span { transform: scale(var(--scale)) ; } .hexagons span:nth-child(1) { --scale: 1; } .hexagons span:nth-child(2) { --scale: calc(1 * 0.9); } .hexagons span:nth-child(3) { --scale: calc(1 * 0.9 * 0.9); } .hexagons span:nth-child(4) { --scale: calc(1 * 0.9 * 0.9 * 0.9); } .hexagons span:nth-child(5) { --scale: calc(1 * 0.9 * 0.9 * 0.9 * 0.9); }
再設置變量,讓六邊形依次傾斜不一樣的角度:
.hexagons span { transform: scale(var(--scale)) rotate(calc(var(--n) * 6deg)); } .hexagons span:nth-child(1) { --n: 1; } .hexagons span:nth-child(2) { --n: 2; } .hexagons span:nth-child(3) { --n: 3; } .hexagons span:nth-child(4) { --n: 4; } .hexagons span:nth-child(5) { --n: 5; }
定義動畫效果:
.hexagons { animation: twist 0.5s linear infinite; } @keyframes twist { from { transform: rotate(0deg) scale(1); } to { transform: rotate(calc(6deg * -2)) scale(1.25); } }
隱藏容器外的內容:
.container { overflow: hidden; }
接下來用 d3 來批量建立六邊形。
引入 d3 庫:
<script src="https://d3js.org/d3.v5.min.js"></script>
用 d3 建立六邊形的 dom 元素:
const COUNT = 5; d3.select('.hexagons') .selectAll('span') .data(d3.range(COUNT)) .enter() .append('span');
用 d3 爲六邊形的 --n 和 --scale 變量賦值:
d3.select('.hexagons') .selectAll('span') .data(d3.range(COUNT)) .enter() .append('span') .style('--scale', (d) => Math.pow(0.9, d)) .style('--n', (d) => d + 1);
刪除掉 html 文件中的六邊形 dom 元素,和 css 文件中聲明的變量。
最後,把六邊形的數量改成 100 個:
const COUNT = 100;
大功告成!