SVG画圆

SVG 基础属性介绍

  • width、height:分别表示 SVG 元素的宽高。
  • viewBox:
  • 前两个参数是对 SVG 元素做位移使用,通常设置为 0;
  • 后两个参数表示 SVG 元素可容纳的大小,具体可参考 SVG 属性之viewBox

circle

  • cx、cy:圆心的位置。
  • r:表示半径。
  • fill:圆的填充色。
  • stroke-width:边框宽度。
  • stroke:边框的填充色。

模拟一个百分比

  • stroke-dasharray:顾名思义,dash 表示虚线,stroke-dash 可理解为将边框设置为虚线,stroke-dasharray 表示这个属性可以接收多个值,实际上一般是接收两个值,例如:
  • stroke-dasharray: 2,2,表示边框的长度是 200,间隔 200 的宽度,再有 200 的虚线长度…,依次类推,呈现的效果是 – – – –
  • stroke-dashoffset:设置边框的偏移距离,这个属性是核心,通过设置它的偏移位置来模拟出百分比。
1
2
3
4
5
6
7
8
9
10
11
<svg width="18px" height="18px" viewBox="0 0 18 18">
<circle
r="7"
cx="9"
cy="9"
fill="#fff"
stroke="#FFC858"
stroke-width="14"
stroke-dasharray="0 44"
:id="`precentCircle${id}`" />
</svg>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@keyframes fillup {
to {
stroke-dasharray: 44 44;
}
}

svg {
transform: rotate(-90deg);

background: #ffc858;

border-radius: 50%;
}

circle {
animation: fillup 5s linear infinite;
}

通过改变 stroke-dasharray 的值来完成饼状效果,其中第一个 44 的值是要画圆的周长,第二个是圆的周长,因为半径一样所以通过覆盖来完成饼状图。