快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

使用CSS和D3实现黑白交叠的动画效果的方法

使用CSS和D3实现黑白交叠的动画效果的方法?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!

网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、小程序开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了晋安免费建站欢迎大家使用!

效果预览

使用CSS和D3实现黑白交叠的动画效果的方法

代码解读

定义 dom,容器中包含 3 个子元素,每个子元素代表一个圆:

居中显示:

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 库:

用 d3 为表示圆数量的变量赋值:

const COUNT_OF_PARTICLES = 30;

d3.select('.circles')
    .style('--particles', COUNT_OF_PARTICLES)

用 d3 生成 dom 元素:

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;

感谢各位的阅读!看完上述内容,你们对使用CSS和D3实现黑白交叠的动画效果的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注创新互联行业资讯频道。


当前题目:使用CSS和D3实现黑白交叠的动画效果的方法
分享网址:http://6mz.cn/article/jeiigc.html

其他资讯