十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
使用CSS和D3实现一个舞动画面的方法?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!
目前创新互联已为上1000+的企业提供了网站建设、域名、雅安服务器托管、网站托管、服务器托管、企业网站设计、雄县网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

https://github.com/comehope/front-end-daily-challenges
定义 dom,容器中包含 1 个 .square 子容器,子容器中包含 4 个 ,每个 代表一个对角扇形:
居中显示:
body {
margin: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: #222;
}设置容器的尺寸单位,1em 等于 8px:
.container {
font-size: 8px;
}子容器中的 4 个 不设宽高,只设边框,其中第 1 个和第 4 个 只取左右边框,第 2 个和第 3 个 只取上下边框:
.square span {
display: block;
border: 2.5em solid transparent;
color: #ddd;
}
.square span:nth-child(1),
.square span:nth-child(4) {
border-left-color: currentColor;
border-right-color: currentColor;
}
.square span:nth-child(2),
.square span:nth-child(3) {
border-top-color: currentColor;
border-bottom-color: currentColor;
}把边框改为圆弧:
.square span {
border-radius: 50%;
}在子容器中用 grid 布局把 4 个 设置为 2 * 2 的网格:
.square {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 0.2em;
padding: 0.1em;
}旋转 4 个 ,使它们围合成一个正方形,看起来像一个花朵,算式的结果是 45 度,写成这样是为了和接下来的动画的算式的形式保持一致:
.square span {
transform: rotate(calc(45deg + 90deg * 0));
}增加让 旋转的动画,整个动画过程旋转 4 次,每次旋转 90 度,4 次旋转之后即返回原位:
.square span {
animation: rotation 2s ease-in-out infinite;
}
@keyframes rotation {
0% { transform: rotate(calc(45deg + 90deg * 0)); }
25% { transform: rotate(calc(45deg + 90deg * 1)); }
50% { transform: rotate(calc(45deg + 90deg * 2)); }
75% { transform: rotate(calc(45deg + 90deg * 3)); }
100% { transform: rotate(calc(45deg + 90deg * 4)); }
}使其中 2 个 朝相反的方向运动:
.square span:nth-child(2),
.square span:nth-child(3) {
animation-direction: reverse;
}至此,一个 .square 子容器的动画已经完成,接下来制作 4 个 .square 的动画。
在 dom 中再增加 3 组 .square 子容器:
用 grid 布局把 4 个 .square 布局成网格状,变量 --columns 是网格的边长,即每边有 2 个 .square 子容器:
.container {
display: grid;
--columns: 2;
grid-template-columns: repeat(var(--columns), 1fr);
}现在看起来好像是有几个黑色的小方块在不停地移动,当 dom 元素越多时,动画效果看起来就越壮观,就像集体舞一样,人越多越有气势。接下来用 d3 批量增加 dom 的元素。
引入 d3 库:
声明一个 COLUMNS 常量,表示网格的边长:
const COLUMNS = 2;
删除掉 html 文件中的 .square 子元素,改为用 d3 动态创建:
d3.select('.container')
.selectAll('p')
.data(d3.range(COLUMNS * COLUMNS))
.enter()
.append('p')
.attr('class', 'square');继续用连缀语法增加 子元素:
d3.select('.container')
.selectAll('p')
.data(d3.range(COLUMNS * COLUMNS))
.enter()
.append('p')
.attr('class', 'square')
.selectAll('span')
.data(d3.range(4))
.enter()
.append('span');删除掉 css 文件中的 --columns 变量声明,改为用 d3 动态声明:
d3.select('.container')
.style('--columns', COLUMNS)
/*略*/最后,把边长改为 4,即让 16 个 .square 一起动画:
const COLUMNS = 4;
感谢各位的阅读!看完上述内容,你们对使用CSS和D3实现一个舞动画面的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注创新互联行业资讯频道。