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-dasharraystroke-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(二)——文本外观属性与复合选择器
前端·css·经验分享·笔记
H Journey1 天前
web开发学习:html、css、js
前端·css·html·js
用户059540174461 天前
AI Agent 记忆存储踩坑实录:这个问题让我排查了 3 天,最终用 pytest + Docker 实现秒级回归
前端·css
今日无bug1 天前
Emmet 语法速成指南
前端·css·html
Hello.Reader1 天前
Tailwind CSS v4.3 从入门到实战Vite 安装、响应式布局、暗黑模式与主题配置
前端·css
cxxcode2 天前
CSS Loader 与样式处理链路
前端·css
CappuccinoRose2 天前
CSS、Less、Sass(含 SCSS)、Stylus
前端·css·less·sass·stylus
用户059540174463 天前
把前端内存泄漏排查从2小时压到5分钟,我们把它集成进了CI
前端·css
zhanghaofaowhrql5 天前
为CSDN博客编辑器安装自定义CSS主题,打造个性化写作界面
前端·css·编辑器
aichitang20245 天前
Claude fable 5与GPT5.5模型能力实测
javascript·css·人工智能·ai·html·html5