如何用 CSS 和 D3 创作一个抽象的黑白交叠动画

在这里插入图片描述

效果预览

在线演示

按下右侧的“点击预览”按钮可以在当前页面预览,点击链接可以全屏预览。

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

可交互视频

此视频是可以交互的,你可以随时暂停视频,编辑视频中的代码。

请用 chrome, safari, edge 打开观看。

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

源代码下载

本地下载

每日前端实战系列的全部源代码请从 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 个圆的底部中点旋转,围成一个更大的圆形:


.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)



<p>用 d3 生成 dom 元素:</p>
<pre class="brush:js">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;
```

大功告成!

原文地址:https://segmentfault.com/a/1190000016047889

猜你喜欢

转载自blog.csdn.net/w178191520/article/details/84891763