如何使用JavaScript根据计算值动态设置SVG环形进度条的百分比
解决SVG环形进度条动态设置百分比的问题
我来帮你搞定这个环形进度条的动态更新问题!核心问题是你没搞明白stroke-dashoffset的工作逻辑——它不能直接用百分比数值赋值,得结合圆的周长来计算才行。
先理清楚核心原理
环形进度条的实现依赖SVG的两个关键属性:
stroke-dasharray:把圆环分成一段段虚线,我们把它设置成和圆周长一样的长度,让整个圆环变成一个完整的"虚线段"。stroke-dashoffset:控制这个虚线段的偏移量。偏移量等于周长时,进度完全隐藏;偏移量为0时,进度满格。我们要做的就是根据百分比,计算出对应的偏移量来显示部分圆环。
具体修复步骤
- 计算圆的精确周长:你的圆环半径是70,周长公式是
2 * π * 半径,我们用代码精确计算。 - 根据百分比推导偏移量:假设
percent是0-1之间的数值(比如25%就是0.25),偏移量公式为:周长 - (周长 * 百分比)。 - 调整CSS基础样式:确保进度圆的
stroke-dasharray设置为周长,初始偏移量设为周长(默认0%进度)。
修改后的完整代码
HTML(仅调整文本ID避免变量冲突)
<div class="box"> <div class="percent"> <svg> <circle cx="70" cy="70" r="70"></circle> <circle id="circ" cx="70" cy="70" r="70"></circle> </svg> <div class="number"> <h2 id="percentText"></h2><span>%</span> </div> </div> </div>
CSS(优化圆环基础样式)
.box .percent { position: relative; width: 140px; height: 140px; } .box .percent svg { width: 100%; height: 100%; } .box .percent svg circle { fill: none; stroke-width: 10; /* 控制圆环厚度,按需调整 */ transform: rotate(-90deg); /* 让进度从顶部开始,可选 */ transform-origin: center; } .box .percent svg circle:nth-child(1) { stroke: #f3f3f3; } .box .percent svg circle:nth-child(2) { stroke: #03a9f4; stroke-dasharray: 439.82; /* 等于2*π*70的精确值 */ stroke-dashoffset: 439.82; /* 初始隐藏全部进度 */ } .box .number { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-family: Arial, sans-serif; }
JavaScript(动态计算并更新)
// 示例数值,替换成你的revenue和investment const revenue = 250; const investment = 1000; const percent = revenue / investment; // 得到0.25(25%) // 获取DOM元素 const progressCircle = document.getElementById("circ"); const percentText = document.getElementById("percentText"); // 计算圆周长 const radius = 70; const circumference = 2 * Math.PI * radius; // 计算目标偏移量 const offset = circumference - (circumference * percent); // 更新进度条和显示文本 progressCircle.style.strokeDashoffset = offset; percentText.textContent = Math.round(percent * 100);
额外提示
- CSS里的
transform: rotate(-90deg)可以让进度从顶部开始,如果你习惯从右侧开始,可以删掉这行。 - 确保SVG的宽高和圆环半径匹配,避免圆环变形。
这样修改后,只要你算出percent数值,进度条就会精准对应显示啦!
内容的提问来源于stack exchange,提问作者Saad Ali
相关产品推荐
相关产品推荐

