css锥形渐变结合SVG实现环形进度条

该文章介绍了如何结合CSS的锥形渐变和SVG元素来创建环形进度条,包括设置圆弧效果、渐变颜色和动态进度更新。通过调整SVG的stroke-dasharray、stroke-dashoffset和stroke-linecap属性,可以实现不同样式的效果。同时,利用JavaScript处理组件的尺寸变化和动画效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

css锥形渐变结合SVG实现环形进度条

准备:

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
      <circle
        id="circle"
        cx="160"
        cy="160"
        r="150"
        stroke="green"
        stroke-dasharray="942"
        stroke-linecap="round"
        stroke-dashoffset="80"
        stroke-width="20"
        fill="transparent"
        transform="rotate(-90, 160, 160)"
      ></circle>
</svg>

demo

JS:

import { useEffect, useRef, useState } from 'react';
import styles from './index.less';
interface RingGradientChartParams {
  barWidth?: number; // 圆弧宽度
  percent?: number; // 百分比占比 注意范围(0-100)
  colorSteps?: string[]; // 柱条渐变颜色
  backgroundColor?: string; // 背景色
}

const IndexPage: React.FC<RingGradientChartParams> = (
  props: RingGradientChartParams,
) => {
  const {
    barWidth = 10,
    percent = 0,
    colorSteps = ['rgba(0, 216, 249, 0)', 'rgba(0, 216, 249, 1)'],
    backgroundColor = 'rgba(0, 216, 249, 0.3)',
  } = props;
  
  const chartRef = useRef<HTMLDivElement>(null);
  const [svgUrl, setSvgUrl] = useState<string>(); // 转为base64
  const [svgString, setSvgString] = useState<string>('');  // svg字符串
  const [boxSize, setBoxSize] = useState<number>(200); // 盒子尺寸

  useEffect(() => {
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        if (entry.contentBoxSize) {
          // Firefox implements `contentBoxSize` as a single content rect, rather than an array
          const contentBoxSize = Array.isArray(entry.contentBoxSize)
            ? entry.contentBoxSize[0]
            : entry.contentBoxSize;
          const { inlineSize, blockSize } = contentBoxSize;
          // 取最小值
          setBoxSize(Math.min(inlineSize, blockSize));
        }
      }
    });
    if (chartRef.current) {
      resizeObserver.observe(chartRef.current);
    }
  }, []);

  useEffect(() => {
    // 实际占比
    const proportion = percent < 0 ? 0 : percent > 100 ? 100 : percent;

    // 半径
    const radius = boxSize / 2 - barWidth / 2;

    // 旋转角度
    // const rotate =
    //   Math.asin(barWidth / 2 / (2 * (radius - barWidth / 2))) * (180 / Math.PI);

    const svgStr = `
      <svg xmlns="http://www.w3.org/2000/svg" width="${boxSize}" height="${boxSize}">
        <circle
            id="circle"
            cx="${boxSize / 2}"
            cy="${boxSize / 2}"
            r="${radius}"
            stroke="green"
            stroke-dasharray="${2 * Math.PI * radius}"
            stroke-linecap="round"
            stroke-dashoffset="${2 * Math.PI * radius * (1 - proportion / 100)}"
            stroke-width="${barWidth}"
            fill="transparent"
            transform="rotate(${-90}, ${boxSize / 2}, ${boxSize / 2})"
        >
        <animate 
            attributeType="XML"
            attributeName="stroke-dashoffset"
            from="${2 * Math.PI * radius}" 
            to="${2 * Math.PI * radius * (1 - proportion / 100)}"
            dur="1s"
        />
        </circle>
      </svg>
    `;
    setSvgString(svgStr);
  }, [boxSize, barWidth, percent]);

  useEffect(() => {
    const base64 = window.btoa(svgString);
    setSvgUrl(`data:image/svg+xml;base64,${base64}`);
  }, [svgString]);
  return (
    <div
      className={styles.ringGradient}
      ref={chartRef}
      style={
        {
          '--mask': `url(${svgUrl})`,
          '--gradient': `conic-gradient(
        ${colorSteps[0]} 0%,
        ${colorSteps[1]} ${percent + 2}%,
        transparent ${percent + 2}%
      )`,
          '--bgColor': backgroundColor,
          '--barWidth': `${barWidth}px`,
        } as React.CSSProperties
      }
    >
      <div className={styles.gradientBar}></div>
    </div>
  );
};
export default IndexPage;

css:

.ringGradient {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  box-shadow: inset 0 0 0 var(--barWidth) var(--bgColor);
}
.gradientBar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: var(--gradient);
  -webkit-mask-image: var(--mask);
  mask-image: var(--mask);
}

最后效果图:
在这里插入图片描述
最后:有问题欢迎评论指正!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值