如何为SVG环形进度条底部添加预期的阴影效果?
SVG环形进度条底部阴影实现方案
之前用线性渐变没达到预期效果,核心原因是线性渐变沿直线方向过渡,没法贴合环形的弧度来模拟自然的底部阴影。这里推荐两种更适配的实现方式:
方法一:使用SVG滤镜实现贴合阴影
SVG的filter可以给任意形状生成贴合的投影,其中feDropShadow能直接跟随环形轮廓生成阴影,是最省心的方案。
示例代码:
<svg width="200" height="200" viewBox="0 0 200 200"> <!-- 定义阴影滤镜 --> <defs> <filter id="ringShadow" x="-20%" y="-20%" width="140%" height="140%"> <feDropShadow dx="0" dy="4" stdDeviation="6" flood-color="#000" flood-opacity="0.3"/> </filter> <!-- 进度条渐变 --> <linearGradient id="progressGrad" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" stop-color="#4CAF50"/> <stop offset="100%" stop-color="#2196F3"/> </linearGradient> </defs> <!-- 背景圆环 --> <circle cx="100" cy="100" r="80" fill="none" stroke="#e0e0e0" stroke-width="16"/> <!-- 带阴影的进度圆环 --> <circle cx="100" cy="100" r="80" fill="none" stroke="url(#progressGrad)" stroke-width="16" stroke-dasharray="502.65" stroke-dashoffset="150.8" stroke-linecap="round" filter="url(#ringShadow)"/> </svg>
- 参数调整说明:
dx/dy控制阴影偏移方向,stdDeviation调整模糊程度,flood-opacity控制阴影透明度,可根据目标效果灵活修改; - 滤镜的
x/y/width/height要设得足够大,避免阴影被SVG视口裁剪。
方法二:用径向渐变模拟底部阴影
如果不想依赖滤镜,可以在进度条下方绘制一个稍大的半透明渐变圆环,模拟自然的底部阴影衰减效果:
示例代码:
<svg width="200" height="200" viewBox="0 0 200 200"> <defs> <!-- 阴影径向渐变:底部深色,向上逐渐透明 --> <radialGradient id="shadowGrad" cx="50%" cy="100%" r="120%" fx="50%" fy="100%"> <stop offset="0%" stop-color="#000" stop-opacity="0.3"/> <stop offset="100%" stop-color="#000" stop-opacity="0"/> </radialGradient> <!-- 进度条渐变 --> <linearGradient id="progressGrad" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" stop-color="#4CAF50"/> <stop offset="100%" stop-color="#2196F3"/> </linearGradient> </defs> <!-- 阴影圆环:比进度条稍大,位置略偏下 --> <circle cx="100" cy="102" r="82" fill="none" stroke="url(#shadowGrad)" stroke-width="18"/> <!-- 背景圆环 --> <circle cx="100" cy="100" r="80" fill="none" stroke="#e0e0e0" stroke-width="16"/> <!-- 进度圆环 --> <circle cx="100" cy="100" r="80" fill="none" stroke="url(#progressGrad)" stroke-width="16" stroke-dasharray="502.65" stroke-dashoffset="150.8" stroke-linecap="round"/> </svg>
- 阴影圆环的半径比进度条大2,Y轴向下偏移2,让阴影集中在底部区域;
- 径向渐变从底部中心向外扩散并逐渐透明,模拟阴影的自然衰减。
这两种方法都能实现贴合环形的底部阴影,你可以根据目标效果的细节调整参数,比如阴影的深浅、模糊度、偏移量等。
内容的提问来源于stack exchange,提问作者Vicky
相关产品推荐
相关产品推荐

