如何实现带虚线边框的SVG圆形进度条并添加动画效果
Got it, let's figure out how to nail both the tutorial's animation and that dashed circular border you want! Here's a straightforward breakdown tailored to your current CSS:
First, Let's Recap the Core Idea
The stroke-dasharray property controls your dashed line pattern—it uses pairs of values for the length of visible dashes and the gaps between them. Your original 1.4308, 1.4308 creates tiny, evenly spaced dashes, but we can tweak this to match your reference image while keeping the animation intact.
Step-by-Step Adjustments
The key is to preserve the animation's logic (using stroke-dashoffset to reveal progress) while updating stroke-dasharray for the dashed style. Here's what to do:
Calculate your circle's perimeter
Grab the radius (rattribute) of your SVG<circle>element. The perimeter is2 * π * r(for example, ifr="45", perimeter ≈ 282.74). You'll need this value for the animation to work correctly.Update your CSS properties
Replace your existingstroke-dasharraywith values that match your desired dashed look. For instance, if you want longer dashes with small gaps, try8, 2(tweak these numbers until it matches your image). Keep the rest of your CSS, and ensure the animation targetsstroke-dashoffset:fill: none; stroke: #FF2A2A; stroke-width: 9.9213; stroke-miterlimit: 10; /* Adjust these values to match your dashed border style */ stroke-dasharray: 8, 2; /* Keep the animation from your tutorial, update offset values below */ animation: progress-fill 2s linear forwards;Set up the animation keyframes
The animation should start with the entire circle hidden (offset equal to the perimeter) and end with it fully visible (offset 0):@keyframes progress-fill { from { stroke-dashoffset: 282.74; /* Replace with your actual circle perimeter */ } to { stroke-dashoffset: 0; } }
Why This Works
stroke-dasharraydefines the dashed pattern that gets drawn as the animation plays out.stroke-dashoffsetcontrols how much of that dashed pattern is hidden at the start—animating it from the perimeter to 0 reveals the full circular progress bar in your desired dashed style.
Quick Tweaking Tips
- Test different
stroke-dasharraypairs (like5, 3or10, 1) to get the exact dashed look from your reference image. - Double-check that the perimeter value in the keyframes matches your circle's actual size—this ensures the animation runs smoothly from start to finish.
内容的提问来源于stack exchange,提问作者Livnat Menashe

