纯 Css 绘制扇形

阅读此文需具有基本数学知识:圆心角、弧度制、三角函数。css

为实现以下效果呕心沥血:html

固然你能够拥抱 Svg...在此分享如何纯 Css 打造圆环进度条,只需三步!git

此物乃 2 + 1 夹心饼干,蓝绿色部分为果酱。显而易见饼干为两个削成了圆形的 div ,咱们重点演示果酱是怎么制做的:github

如图所示,大扇形由 6 个小扇形构成,每一小扇形占整个圆饼的 1/15 ,大扇形占整个圆饼的 6/15 。咱们只需构造一个扇形单元,将其复制 6 份后旋转相应角度链接至一块儿便可。web

如何构造扇形?用三角形假装...segmentfault

三角形的宽高如何计算?假定圆半径 $radius 为 100px,等分数 $count 为 15。则小扇形的圆心角为 360deg / 15 ,三角形的高为 100px,宽为 2 × 100px × tan(360deg / 15 / 2) 。其中 360deg / 15 / 2 转化弧度制为 PI / 15 (PI == 360deg / 2)。sass

span {
    width: 0;
    height: 0;
    border: $radius solid transparent;
    $borderWidth: tan(pi() / $count) * $radius;
    border-left-width: $borderWidth;
    border-right-width: $borderWidth;
}

数学欠佳的同窗请自行科普...bash

对于 $count12 的状况需特殊处理,由于 tan(PI)tan(PI / 2) 为无穷值,不了解的同窗请研究正切函数图像:函数

相关代码(其中 $diameter = 2 × $radius 为圆直径):post

span {
    @if $count == 1 {
        width: $diameter;
        height: $diameter;
    } @else if $count == 2 {
        width: $diameter;
        height: $radius;
    } @else {
        width: 0;
        height: 0;
        border: $radius solid transparent;
        $borderWidth: tan(pi() / $count) * $radius;
        border-left-width: $borderWidth;
        border-right-width: $borderWidth;
    }
}

最后,复制并逐一旋转扇形单元:

@for $index from 0 to $count {
    span:nth-child(#{$index + 1}) {
        $transform: translate(-50%, 0) rotate(360deg / $count / 2 + 360deg * $index / $count);
        $origin: if($count == 2, bottom, center);
        -webkit-transform: $transform;
                transform: $transform;
        -webkit-transform-origin: $origin;
                transform-origin: $origin;
    }
}

果酱制做完毕,其它点缀请自行添加喽...本例完整代码在此


2017/11/14 续更

因为本例引入了三角函数等数学运算,使用 Sass 预编译。未安装 Sass 的同窗可下载经编译的 源码 开启 sector.html 查看效果。

安装 Sass 请参考 https://segmentfault.com/a/11... 文章末尾的安装教程。

本例调试方法:

cd sector
sass --watch style.scss:style.css --debug-info

做者:呆恋小喵

个人后花园:https://sunmengyuan.github.io...

个人 github:https://github.com/sunmengyuan

原文连接:https://sunmengyuan.github.io...

相关文章
相关标签/搜索