前端每日實戰:139# 視頻演示如何用 CSS 和 D3 創作光斑粒子交相輝映的動畫

圖片描述

效果預覽

按下右側的“點擊預覽”按鈕可以在當前頁面預覽,點擊鏈接可以全屏預覽。

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

可交互視頻

此視頻是可以交互的,你可以隨時暫停視頻,編輯視頻中的代碼。

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

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

源代碼下載

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

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

代碼解讀

定義 dom,容器中包含 3 個子元素:

<div class='container'>
    <span></span>
    <span></span>
    <span></span>
</div>

設置頁面背景:

body {
    margin: 0;
    width: 100vw;
    height: 100vh;
    background: radial-gradient(circle at center, #222, black 20%);
}

定義容器尺寸:

.container {
    width: 100%;
    height: 100%;
}

設置光斑的樣式,其中定義了偏亮和偏暗的 2 個顏色變量:

.container {
    position: relative;
}

.container span {
    --bright-color: #d4ff00;
    --dark-color: #e1ff4d;
    position: absolute;
    width: 30px;
    height: 30px;
    margin-left: -15px;
    margin-top: -15px;
    background: radial-gradient(var(--bright-color), var(--dark-color));
    border-radius: 50%;
    box-shadow: 0 0 25px 3px var(--dark-color);
}

把光斑定位到頁面中心:

.container span {
    transform: translateX(50vw) translateY(50vh);
}

增加光斑從中心向四周擴散和收縮的動畫效果:

.container span {
    animation: animate 1.5s infinite alternate;
    animation-delay: calc(var(--n) * 0.015s);
}

@keyframes animate {
    80% {
        filter: opacity(1);
    }

    100% {
        transform: translateX(calc(var(--x) * 1vw)) translateY(calc(var(--y) * 1vh));
        filter: opacity(0);
    }
}

定義動畫中用到的變量 --x--y--n

.container span:nth-child(1) {
    --x: 20;
    --y: 30;
    --n: 1;
    
}

.container span:nth-child(2) {
    --x: 60;
    --y: 80;
    --n: 2;
}

.container span:nth-child(3) {
    --x: 10;
    --y: 90;
    --n: 3;
}

設置容器的景深,使光斑的運動有從遠到近的感覺:

.container {
    perspective: 500px;
}

.container span {
    transform: translateX(50vw) translateY(50vh) translateZ(-1000px);
}

至此,少量元素的動畫效果完成,接下來用 d3 批量創建 dom 元素和 css 變量。
引入 d3 庫,同時刪除 html 文件中的子元素和 css 文件中的子元素變量:

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

定義光斑粒子數量:

const COUNT = 3;

批量創建 dom 元素:

d3.select('.container')
    .selectAll('span')
    .data(d3.range(COUNT))
    .enter()
    .append('span');

爲 dom 元素設置 --x--y--n 的值,其中 --x--y 是 1 到 99 的隨機數:

d3.select('.container')
    /* 略 */
    .style('--x', () => d3.randomUniform(1, 99)())
    .style('--y', () => d3.randomUniform(1, 99)())
    .style('--n', d => d);

再爲 dom 元素設置 --bright-color--dark-color 的值:

d3.select('.container')
    /* 略 */
    .style('--dark-color', (d) => d3.color(`hsl(${70 + d * 0.1}, 100%, 50%)`))
    .style('--bright-color', (d) => d3.color(`hsl(${70 + d * 0.1}, 100%, 50%)`).brighter(0.15));

最後,把光斑粒子數量設置爲 200 個:

const COUNT = 200;

大功告成!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章