纯CSS绘制太极图

937 阅读2分钟

这是我参与8月更文挑战的第20天,活动详情查看:8月更文挑战

问题起源

前几天不知道写什么,在沸点上问工友们(敲黑板,官方口径)前端还有什么画起来有点儿意思的:

CSS不知道写啥了,兄弟们给出道题目吧

某位工友说画太极图,恩~太极图长这个样子:

image.png

有点儿复杂,我们来画一下试试。

圆的绘制

按照我们之前的CSS文章,我们目前有两种画圆策略:

  1. 对正方形使用border-radius: 50%
  2. 对图形使用cli-path: cirlcle(..)截取圆形

第一种border-radius显然要简单一些。

图形拆解与绘制

太极图可以拆分为左右两侧黑白两个半圆,上下两部分又分别有一个大圆环。

按照思路我们来一一绘制。

两个半圆

  1. 我们先绘制两个紧挨着的矩形:

image.png

<!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>
  1. 分别添加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;
    }

image.png

  1. 对上半部和下半部分别添加圆环:

在HTML部分,添加两个div: taiji-toptaiji-bottom,其CSS通过设置较大的borderborder-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>

image.png

  1. 修改为对应border颜色:

image.png

结论

看起来容易做起来难。

去网上搜了一下,有的大神用一个DIV实现了,看了一下思路,减少DOM的大概思路有:

  1. 使用伪元素::before::after来代替html的DIV.
  2. 使用box-shadow来模拟DOM
  3. 使用两边定义不同的border来生成一边黑,一边白的圆形。