这是我参与8月更文挑战的第20天,活动详情查看:8月更文挑战
问题起源
前几天不知道写什么,在沸点上问工友们(敲黑板,官方口径)前端还有什么画起来有点儿意思的:
某位工友说画太极图,恩~太极图长这个样子:
有点儿复杂,我们来画一下试试。
圆的绘制
按照我们之前的CSS文章,我们目前有两种画圆策略:
- 对正方形使用
border-radius: 50% - 对图形使用
cli-path: cirlcle(..)截取圆形
第一种border-radius显然要简单一些。
图形拆解与绘制
太极图可以拆分为左右两侧黑白两个半圆,上下两部分又分别有一个大圆环。
按照思路我们来一一绘制。
两个半圆
- 我们先绘制两个紧挨着的矩形:
<!DOCTYPE html>
<title>太极图</title>
<body>
<div class="taiji-left"></div>
<div class="taiji-right"></div>
</body>
<style>
body {
width: 100vw;
height: 100vh;
background: lightblue;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.taiji-left {
height: 300px;
width: 150px;
background: black;
}
.taiji-right {
height: 300px;
width: 150px;
background: white;
}
</style>
</html>
- 分别添加
border-radius:
.taiji-left {
height: 300px;
width: 150px;
background: black;
/*重点*/
border-radius: 150px 0 0 150px ;
}
.taiji-right {
height: 300px;
width: 150px;
background: white;
/*重点*/
border-radius: 0 150px 150px 0;
}
- 对上半部和下半部分别添加圆环:
在HTML部分,添加两个div: taiji-top和taiji-bottom,其CSS通过设置较大的border与border-radius从而呈现圆环效果。
代码:
<!DOCTYPE html>
<title>太极图</title>
<body>
<div class="taiji-left">
<div class="taiji-top"></div>
</div>
<div class="taiji-right">
<div class="taiji-bottom"></div>
</div>
</body>
<style>
body {
width: 100vw;
height: 100vh;
background: lightblue;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.taiji-left {
height: 400px;
width: 200px;
background: black;
border-radius: 200px 0 0 200px ;
position: relative;
}
.taiji-right {
height: 400px;
width: 200px;
background: white;
border-radius: 0 200px 200px 0;
position: relative;
}
.taiji-top {
border: 75px solid red;
width: 50px;
height: 50px;
background: white;
position: absolute;
top: 0;
right: -100px;
border-radius: 50%;
z-index: 2;
}
.taiji-bottom {
border: 75px solid red;
width: 50px;
height: 50px;
background: black;
position: absolute;
bottom: 0;
left: -100px;
border-radius: 50%;
}
</style>
</html>
- 修改为对应
border颜色:
结论
看起来容易做起来难。
去网上搜了一下,有的大神用一个DIV实现了,看了一下思路,减少DOM的大概思路有:
- 使用伪元素
::before与::after来代替html的DIV. - 使用
box-shadow来模拟DOM - 使用两边定义不同的border来生成一边黑,一边白的圆形。