根据线性渐变中的颜色更改SVG圆形进度条的描边

3

我正在尝试使用CSS和JavaScript(以及React)使SVG圆形进度条根据进度/百分比从线性渐变中改变颜色。

到目前为止,我找到的每个解决方案都有硬编码的颜色代码或使用jQuery,而我无法使用。下面是我的代码和CSS:

  <svg viewBox="0 0 36 36" className="circular-chart">
  <path className="svg-back"
    fill='none'
    stroke={props.theme.colors.Neutral.Gray1}
    strokeWidth={3}
    d="M18 2.0845
  a 15.9155 15.9155 0 0 1 0 31.831
  a 15.9155 15.9155 0 0 1 0 -31.831"
  />
  <path className="circle"
    stroke-dasharray={`${props.percentage} 100`}
    d="M18 2.0845
  a 15.9155 15.9155 0 0 1 0 31.831
  a 15.9155 15.9155 0 0 1 0 -31.831"
  />

  <text
    x={18}
    y={21}
    className="svg-circle-text">
    {props.percentage}%
  </text>
</svg>

CSS:
    .svg-circle-text {
      font-size: 0.5rem;
      text-anchor: middle;
      fill: ${theme.colors.Primary.Black}
      font-weight: bold;
  }

  .circular-chart {
    display: block;
    margin: 10px auto;
    max-width: 80%;
    max-height: 250px;
  }
  
  .circle {
    stroke: #99DA98;
    fill: none;
    stroke-width: 3;
    stroke-linecap: round;
    animation: progress 1s ease-out forwards;
  }
  
  @keyframes progress {
    0% {
      stroke-dasharray: 0 100;
    }
  }

在另一个组件中,我有以下背景色,它作为这个圆形进度条的一种关键作用:
 background: linear-gradient(
      90deg,
      #99da98 0%,
      #f8b66a 51.56%,
      #cf6767 100%
    );

如果百分比为60%,则应该显示60%处的渐变值。希望能得到一些帮助。谢谢。


我看不到%符号的设置在哪里。 - A Haworth
@AHaworth,它在SVG的第二个路径中,stroke-dasharray={${props.percentage} 100} - momal
你尝试过使用HSL吗? - Matan Sanbira
@MatanSanbira,那听起来像是一个可能的解决方案。我不知道这个,会去看一下。 - momal
你可以对 r g b 设置进行一些算术运算,因为它们是线性的,至少在这两个区间内。 - A Haworth
1个回答

2

在A Haworth留下的评论的帮助下,我搜索了rgb算法解决方案,并在这个答案中找到了几乎完全符合我要求的内容。hsl也是一个选项,但rgb听起来足够简单。通过对以下代码(来自其他问题)进行一些更改,我成功地实现了我想要的效果。

function getGreenToRed(percent){
            r = percent<50 ? 255 : Math.floor(255-(percent*2-100)*255/100);
            g = percent>50 ? 255 : Math.floor((percent*2)*255/100);
            return 'rgb('+r+','+g+',0)';
        }

1
好的,哇,这对我有帮助。不过,我返回使用模板字面量,如 rgb(${r},${g},0) - Edd Chang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接