如何用 CSS 和 D3 创作一个抽象的黑白交叠动画
效果預(yù)覽
在線演示按下右側(cè)的“點擊預(yù)覽”按鈕可以在當(dāng)前頁面預(yù)覽,點擊鏈接可以全屏預(yù)覽。
https://codepen.io/comehope/pen/Yjomyd
可交互視頻
此視頻是可以交互的,你可以隨時暫停視頻,編輯視頻中的代碼。
請用 chrome, safari, edge 打開觀看。
https://scrimba.com/p/pEgDAM/cydZrfr
源代碼下載
本地下載每日前端實戰(zhàn)系列的全部源代碼請從 github 下載:
https://github.com/comehope/front-end-daily-challenges
代碼解讀
定義 dom,容器中包含 3 個子元素,每個子元素代表一個圓:
<div class="circles"><span></span><span></span><span></span> </div>居中顯示:
body {margin: 0;height: 100vh;display: flex;align-items: center;justify-content: center;background-color: black; }定義容器尺寸:
.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 個圓的底部中點旋轉(zhuǎn),圍成一個更大的圓形:
.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);} }設(shè)置子元素混色模式,使子元素間交疊的部分顯示成黑色:
.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 庫:
用 d3 為表示圓數(shù)量的變量賦值:
const COUNT_OF_PARTICLES = 30;d3.select(’.circles’)
.style(’–particles’, COUNT_OF_PARTICLES)
用 d3 為表示子元素下標(biāo)的變量賦值:
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 文件中的相關(guān) dom 元素和 css 文件中相關(guān)的 css 變量。
最后,把圓的數(shù)量調(diào)整為 30 個:
const COUNT_OF_PARTICLES = 30; ```大功告成!
原文地址:https://segmentfault.com/a/1190000016047889總結(jié)
以上是生活随笔為你收集整理的如何用 CSS 和 D3 创作一个抽象的黑白交叠动画的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mysql大型数量下的数据库构建的30条
- 下一篇: java日志处理汇总