首页 > 解决方案 > 如何创建具有 4 个扇区的圆形 SVG?

问题描述

我为一个有 4 个扇区的圆圈创建了一个代码。是否有任何在线 SVG 生成器可以在 SVG 中创建下面的圆圈,或者任何人都可以帮助我使用 SVG 代码?为什么我在 SVG 中创建,因为我必须在每个扇区中添加文本。

我在下面的链接中找到了,但这不是我的预期输出。 SVG画一个有4个扇区的圆

在此处输入图像描述

.wrap {
  position: relative;
}

.circle-donut {
  width: 250px;
  height: 250px;
  border-radius: 50%;
  border-top: 140px solid #a3fe01;
  border-bottom: 140px solid #2800eb;
  border-right: 140px solid #dd6479;
  border-left: 140px solid #ead52c;
}

.inlineWrap {
  position: relative;
}

.absolute {
  position: absolute;
}

.inlineWrap .top {
  top: 0;
}

.inlineWrap .bottom {
  bottom: 0;
}

.inlineWrap .left {
  left: 0;
}

.inlineWrap .right {
  right: 0;
}
<div class="wrap">
  <div class="circle-donut"></div>
</div>

标签: htmlcsssvg

解决方案


您可以使用 stroke-dasharray = ".25 * tl .75 * tl" 的同一个圆的 4 倍,其中 tl 是圆周的总长度,计算为圆的周长或使用该getTotalLength()方法计算。

对于第一个使用元素,stroke-dashoffset = 1/8 * tf 周长。第二个使用元素有 stroke-dashoffset = 1/8 * tf + 1/4tf 第三个有 stroke-dashoffset = 1/8 * tf + 2/4tf... 等等

svg{width:95vh}
<svg viewBox="-50 -50 100 100">
<defs>
  <circle id="c" r="40" stroke-width="20" fill="none" stroke-dasharray="62.75 188.25" />
</defs>
  <use xlink:href="#c" stroke="red" stroke-dashoffset="31.375"/>
    <use xlink:href="#c" stroke="gold" stroke-dashoffset="94.125"/>
   <use xlink:href="#c" stroke="blue" stroke-dashoffset="156.875"/> 
     <use xlink:href="#c" stroke="orange" stroke-dashoffset="219.625"/>
</svg>

或者,您可以将圆旋转 -45 度,而不是每次使用 1/8 * tf

svg{width:95vh}
<svg viewBox="-50 -50 100 100">
<defs>
  <circle id="c" r="40" stroke-width="20" fill="none" stroke-dasharray="62.75 188.25" transform="rotate(-45)" />
</defs>
  <use xlink:href="#c" stroke="red" stroke-dashoffset="0"/>
    <use xlink:href="#c" stroke="gold" stroke-dashoffset="62.75"/>
   <use xlink:href="#c" stroke="blue" stroke-dashoffset="125.5"/> 
     <use xlink:href="#c" stroke="orange" stroke-dashoffset="188.25"/>
</svg>

更新

OP正在评论

你能帮我弄清楚如何在扇区内显示文本吗?

正如我对此评论的那样,您需要向 svg 元素添加一些文本元素。文本元素使用 css 居中:text-anchor:middle;dominant-baseline:middle;

由于所有绘图都以点 x:0,y:0 为中心,因此您需要使用圆 (40) 的半径值来获取文本的 x 或 y。如果缺少 x 或 y,这意味着它的值为 0。

svg{width:95vh}

text{text-anchor:middle;dominant-baseline:middle;font-size:10px;}
<svg viewBox="-50 -50 100 100">
    <defs>
      <circle id="c" r="40" stroke-width="20" fill="none" stroke-dasharray="62.75 188.25" />
    </defs>
      <use xlink:href="#c" stroke="red" stroke-dashoffset="31.375"/>
        <use xlink:href="#c" stroke="gold" stroke-dashoffset="94.125"/>
       <use xlink:href="#c" stroke="blue" stroke-dashoffset="156.875"/> 
         <use xlink:href="#c" stroke="orange" stroke-dashoffset="219.625"/>
         
        <text x="40">red</text>
        <text y="40">orange</text>
        <text x="-40">blue</text>
        <text y="-40">gold</text> 
         
    </svg>


推荐阅读