按下右侧的“点击预览”按钮能够在当前页面预览,点击连接能够全屏预览。javascript
https://codepen.io/comehope/pen/QBQJMgcss
此视频是能够交互的,你能够随时暂停视频,编辑视频中的代码。html
请用 chrome, safari, edge 打开观看。前端
https://scrimba.com/p/pEgDAM/c9mydU8java
每日前端实战系列的所有源代码请从 github 下载:git
https://github.com/comehope/front-end-daily-challengesgithub
定义 dom,容器中包含 3 個元素,表明蠕虫的 3 个体节:chrome
<div class="worm"> <span></span> <span></span> <span></span> </div>
居中显示:app
body { margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background-color: #222; }
画出蠕虫最大的体节:dom
.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;
大功告成!