乐闻世界logo
搜索文章和话题

SVG 如何实现渐变和滤镜效果

2月21日 15:20

SVG 提供了强大的渐变和滤镜功能,可以创建丰富的视觉效果:

1. 渐变(Gradients) SVG 支持线性渐变和径向渐变,需要在 <defs> 中定义,然后通过 fillstroke 引用。

线性渐变(linearGradient)

svg
<svg width="200" height="100"> <defs> <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" /> <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" /> </linearGradient> </defs> <rect width="200" height="100" fill="url(#grad1)" /> </svg>

属性说明:

  • x1, y1, x2, y2:渐变线的起点和终点坐标
  • gradientUnits:坐标系统(userSpaceOnUse 或 objectBoundingBox)
  • gradientTransform:渐变变换
  • spreadMethod:渐变扩展方式(pad, reflect, repeat)

径向渐变(radialGradient)

svg
<svg width="200" height="200"> <defs> <radialGradient id="grad2" cx="50%" cy="50%" r="50%" fx="50%" fy="50%"> <stop offset="0%" style="stop-color:white;stop-opacity:1" /> <stop offset="100%" style="stop-color:blue;stop-opacity:1" /> </radialGradient> </defs> <circle cx="100" cy="100" r="90" fill="url(#grad2)" /> </svg>

属性说明:

  • cx, cy, r:外圆的中心和半径
  • fx, fy:焦点位置(渐变中心)

2. 滤镜(Filters) SVG 滤镜可以应用各种视觉效果,如模糊、阴影、发光等。

模糊滤镜(feGaussianBlur)

svg
<svg width="200" height="100"> <defs> <filter id="blur"> <feGaussianBlur in="SourceGraphic" stdDeviation="5" /> </filter> </defs> <rect width="100" height="50" fill="blue" filter="url(#blur)" /> </svg>

阴影滤镜(feDropShadow)

svg
<svg width="200" height="100"> <defs> <filter id="shadow"> <feDropShadow dx="5" dy="5" stdDeviation="3" flood-color="black" flood-opacity="0.5" /> </filter> </defs> <rect x="50" y="25" width="100" height="50" fill="red" filter="url(#shadow)" /> </svg>

发光滤镜(feGaussianBlur + feMerge)

svg
<svg width="200" height="100"> <defs> <filter id="glow"> <feGaussianBlur stdDeviation="3.5" result="coloredBlur"/> <feMerge> <feMergeNode in="coloredBlur"/> <feMergeNode in="SourceGraphic"/> </feMerge> </filter> </defs> <text x="100" y="50" font-size="30" fill="yellow" filter="url(#glow)" text-anchor="middle">Glow</text> </svg>

常用滤镜元素:

  • feGaussianBlur:高斯模糊
  • feDropShadow:阴影
  • feOffset:偏移
  • feColorMatrix:颜色矩阵变换
  • feBlend:混合模式
  • feComposite:合成
  • feMerge:合并
  • feFlood:填充颜色

3. 组合使用

svg
<svg width="300" height="200"> <defs> <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%"> <stop offset="0%" stop-color="#ff6b6b" /> <stop offset="100%" stop-color="#4ecdc4" /> </linearGradient> <filter id="shadow"> <feDropShadow dx="3" dy="3" stdDeviation="2" flood-color="#000" flood-opacity="0.3" /> </filter> </defs> <rect x="50" y="50" width="200" height="100" rx="10" ry="10" fill="url(#grad)" filter="url(#shadow)" /> </svg>

性能优化建议:

  • 滤镜是性能密集型操作,谨慎使用
  • 简单效果优先使用 CSS
  • 复杂效果考虑使用 Canvas
  • 避免在动画中使用复杂滤镜
标签:SVG