如何从左侧开始按百分比将颜色填充到甜甜圈 SVG 路径?

How to fill a color to a donut SVG path by percentage by starting from left side?

我有一个甜甜圈 SVG 路径。填充颜​​色必须从左侧开始,必须从右侧结束,并且必须按百分比填充。

看到这个:


(来源:eksiup.com

我试过像这样实现这个旋转的 clipPath:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 92 100">
<defs>
  <clipPath id="knobMask">
      <path style="fill: #ff554e;" d="
            M 17.72, 74.28
           a 40, 40,0, 1, 1, 56.56, 0
           l 4.25, 4.25
           a 46, 46, 0, 1, 0-65.06 ,0 Z" />
</clipPath>
</defs>
<g>
<g id="Layer_1" data-name="Layer 1">
  <g id="Path_34688-6" data-name="Path 34688-6">
    />
  </g>
  <path d="M17.72,74.28a40,40,0,1,1,56.56,0l4.25,4.25a46,46,0,1,0-65.06,0Z" />

  <g clip-path="url(#knobMask)" transform="rotate(-45,45,45)">
    <path style="fill: #ff554e;" d="M 17.72,74.28
            a 40,40,0,1,1,56.56,0
            l 4.25,4.25
            a 46,46,0,1,0-65.06,0Z" />
  </g>
</g>

但运气不好。如何从左侧开始按百分比向该路径填充颜色?

Here is the JS Fiddle

基本上我想要这个:


(来源:eksiup.com

正如我所说,有一种更简单的方法可以实现这一点。您将路径简化为 d="M 17.72,74.28a 40,40,0,1,1,56.56,0" 并使用 fill="none" 和 stroke="10" 例如。对于红色路径,您使用与之前相同的 d 并使用 stroke-dasharray 来减少路径的表观长度。如果您使用此 d,则路径的总长度为 188.53,因此您可以使用 188.53 / 2 = 94.265 :stroke-dasharray=94.265"

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 92 100" width="200">
<defs>
      <path id="base" fill="none" stroke-width="10" d="
            M 17.72, 74.28
           a 40, 40,0, 1, 1, 56.56, 0" />
 </defs> 
  <use xlink:href="#base" stroke="black"  />
  <use xlink:href="#base" stroke="#ff554e" stroke-dasharray="94.265"  />

  </svg>

在下一个示例中,我将使用 javascript 来计算破折号的值和间隙的值。请使用输入类型范围来更改值。

let totallength=base.getTotalLength();

itr.addEventListener("input",()=>{
let newSDA = (Number(itr.value)*totallength) / 100;
let gap = totallength - newSDA

red.setAttributeNS(null,"stroke-dasharray",`${newSDA} ${gap}`)
})
svg{border:1px solid}
<p><input id="itr" type="range"  /></p>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 92 100" width="200">
<defs>
      <path id="base" fill="none" stroke-width="10" d="
            M 17.72, 74.28
           a 40, 40,0, 1, 1, 56.56, 0" />
 </defs> 
  <use xlink:href="#base" stroke="black"  />
  <use xlink:href="#base" id="red" stroke="#ff554e" stroke-dasharray="94.265"  />

  </svg>