温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-28 14:17:00 来源:亿速云 阅读:197 作者:小新 栏目:web开发

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

效果预览

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

代码解读

定义 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)

用 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实现黑白交叠的动画效果的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

css
AI