跳到主要内容

简单的饼图

先画一个圆,左右分为两半,左边为颜色1,右边为颜色2。然在这个圆上再画一个相同圆心、相同半径、颜色为2的半圆。

当这个半圆围绕圆心旋转时,会和颜色2的另一半发生融合,产生在一个左右部分为不同颜色的圆形上,画一个半圆,半圆围绕圆心旋转的时候,会显示出不同的比率饼图。

0~50% 比率的饼图:

.pie {
width: 100px;
height: 100px;
border-radius: 50%;
background: yellowgreen;
background-image: linear-gradient(to right, transparent 50%, currentColor 0);
color: #655;
}

.pie::before {
content: "";
display: block;
margin-left: 50%;
height: 100%;
border-radius: 0 100% 100% 0 / 50%;
background-color: inherit;
transform-origin: left;
transform: rotate(0.2turn);
}

效果图:

把半圆的背景换成另外一种颜色,即可实现 50%~100% 比率的饼图:

.pie2 {
width: 100px;
height: 100px;
border-radius: 50%;
background: yellowgreen;
background-image: linear-gradient(to right, transparent 50%, currentColor 0);
color: #655;
}

.pie2::before {
content: "";
display: block;
margin-left: 50%;
height: 100%;
border-radius: 0 100% 100% 0 / 50%;
background-color: currentColor;
transform-origin: left;
transform: rotate(0.2turn);
}

效果图:

将上面两个结合起来,可以实现一个动态的进度指示器,思路:如果整个动画持续时间是 6 秒,给半圆设置一个持续旋转的动画,在中间时间 3 秒的时候将半圆的背景色替换为另一种颜色。

.pie {
width: 100px;
height: 100px;
border-radius: 50%;
background: yellowgreen;
background-image: linear-gradient(to right, transparent 50%, currentColor 0);
color: #655;
}

.pie::before {
content: "";
display: block;
margin-left: 50%;
height: 100%;
border-radius: 0 100% 100% 0 / 50%;
background-color: inherit;
transform-origin: left;
animation: spin 3s linear infinite, bg 6s step-end infinite;
}

@keyframes spin {
to {
transform: rotate(0.5turn);
}
}
@keyframes bg {
50% {
background: currentColor;
}
}

效果图:

如果我们为上面的动画设置一个负数的动画延时animation-delay,并且把动画播放状态 animation-play-state 设置为paused,动画将会停留在延时值绝对值所在的帧。

饼图显示的比率=负的延时值的绝对值/总动画时间。

在下面的示例中,设置了 -1.2s 的动画延时,占据总时长 6s 的 20%,即画出了一个 20% 比率的饼图:

.pie {
width: 100px;
height: 100px;
border-radius: 50%;
background: yellowgreen;
background-image: linear-gradient(to right, transparent 50%, #655 0);
color: #655;
}

.pie::before {
content: "";
position: absolute;
top: 0;
left: 50%;
width: 50%;
height: 100%;
border-radius: 0 100% 100% 0 / 50%;
background-color: inherit;
transform-origin: left;
animation: spin 3s linear infinite, bg 6s step-end infinite;
animation-play-state: paused;
animation-delay: -1.2s;
}

@keyframes spin {
to {
transform: rotate(0.5turn);
}
}

@keyframes bg {
50% {
background: currentColor;
}
}

效果图: