svg画进度条

直接返回一个进度条的组件,代码如下所示:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>环形进度条</title>
    <style>
        .progress-ring {
            position: relative;
            width: 20px;
            height: 20px;
        }
        
        .progress-ring__circle {
            fill: none;
            stroke-width: 2; /* 调整线条宽度 */
            transform: rotate(-90deg);
            transform-origin: 50% 50%;
        }
        
        .progress-ring__background {
            stroke: #e6e6e6;
        }
        
        .progress-ring__indicator {
            stroke: #4db8ff;
            stroke-dasharray: 50.2655;
            stroke-dashoffset: 50.2655;
            transition: stroke-dashoffset 0.35s;
        }
    </style>
</head>
<body>
    <div class="progress-ring">
        <svg width="20" height="20">
            <circle class="progress-ring__circle progress-ring__background" cx="10" cy="10" r="8"></circle>
            <circle class="progress-ring__circle progress-ring__indicator" cx="10" cy="10" r="8"></circle>
        </svg>
    </div>

    <script>
        function setProgress(progress) {
            const radius = 8;
            const circumference = 2 * Math.PI * radius;
            const circle = document.querySelector('.progress-ring__indicator');
            
            circle.style.strokeDasharray = circumference;
            circle.style.strokeDashoffset = circumference - (circumference * progress / 100);
        }

        setProgress(75);
    </script>
</body>
</html>

解释一下:

  1. 在svg里面画圆形,一个circle是底部的灰色,另一个是填充的进度样式;

  2. 起始点:transform: rotate(-90deg);是设置开始的点,-90是从顶部开始,这里需要去查一下这个用法如果设置0的话就会从右侧开始,像下面:

那么180就是左侧开始,这是起始点;

3)stroke-dasharray 和 stroke-dashoffset 用于控制进度条的长度和进度。stroke-dasharray 设置为圆圈周长,stroke-dashoffset 初始时也是圆圈周长,表示进度为 0%,初始值就是这么来的:

在我们根据进度变化的时候,因为填充的环开始没有背景色 ,所以0%的时候就是全周长。

progress-ring__indicator样式需要去填充进度的时候,用周长 - 已经执行的进度,那也就是剩下没有颜色的长度,那么就会从顶部开始顺时针的移动,移动过的圆环部分,会填充上stroke: #4db8ff;这个颜色,直到strokeDashoffset为0,那么意思就是填充了全部,也就是100%,这个是需要理解下标签的用法的;

特别是这个offset属性,circle.style.strokeDashoffset = offset;:设置 stroke-dashoffset,将未填充的部分"隐藏"在圆圈的起始点前面,从而显示 75% 的进度。

换句话说,这个进度是顺时针的,如果你想逆时针,你就加一个负号在前面就行了。

相关推荐
思码梁田11 小时前
CSS transform 转换详解:translate、rotate、scale、skew 与 3D 变换一次讲清
前端·css·transform·skew·scale·translate·rotate
三天不学习1 天前
Tailwind CSS 快速入门(2026 版):从 v4 零配置上手,到「该不该用、怎么用好」的选型实战
前端·css·tailwind
htzyl2061 天前
前端阶梯——第九章、颜色、文本与背景
前端·css
htzyl2061 天前
前端阶梯——第八章、CSS入门与选择器
前端·css
传人2 天前
页面中心圆圈放大效果如何写
前端·css
被摘下的星星3 天前
CSS 基础说明
前端·css
学术 学术 Fun3 天前
Cricut 笔绘、烫金和划线如何制作单线 SVG
svg·矢量图·cricut
传人once3 天前
网页文字滚动效果如何做
前端·css·html·jquery·html5
乌暮4 天前
拆解网页的底层逻辑:用费曼学习法讲透 HTML 与 CSS
前端·css·学习·html
传人once4 天前
多图片上传预览功能如何写
前端·css·html·jquery·html5