You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

应用filter后SVG rect的rx属性失效,如何保留圆角效果?

解决SVG rect应用filter后rx圆角失效的问题

问题根源

你的代码中给filter设置了filterUnits="userSpaceOnUse",这个属性会让滤镜以整个SVG画布的坐标系处理内容,而非目标元素(rect)自身的边界框坐标系。这导致滤镜渲染时无法正确识别rect的rx圆角属性,最终丢失圆角效果。

解决方案

去掉filterUnits="userSpaceOnUse"(objectBoundingBox是filter的默认值,可直接省略该属性),或者将其改为filterUnits="objectBoundingBox",就能让滤镜基于元素自身边界框处理,保留圆角效果。

修改后的完整代码

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
  <defs>
    <filter id="floodFilter">
      <feFlood
        flood-color="#488764"
        flood-opacity="1" 
        result="background"
        />
        <feBlend mode="normal" in="SourceGraphic" in2="background" />
    </filter>
    
    <linearGradient id="animation">
           <stop offset="0" stop-color="rgba(248, 222, 86, 0)"/>
           <stop offset="100%" stop-color="#65ae83"/>
        </linearGradient>
  </defs>
  <rect width="100" height="200" filter="url(#floodFilter)" fill="url(#animation)" rx="8">
   <animate attributeType="XML" attributeName="x" from="-100" to="100" dur="1s" repeatCount="indefinite"/>
  </rect>
</svg>

备选方案(若需保留userSpaceOnUse)

如果因其他滤镜逻辑必须保留userSpaceOnUse,可将rect包裹在<g>标签内,把filter应用到<g>上,rect自身保留rx属性:

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
  <defs>
    <filter id="floodFilter" filterUnits="userSpaceOnUse">
      <feFlood
        flood-color="#488764"
        flood-opacity="1" 
        result="background"
        />
        <feBlend mode="normal" in="SourceGraphic" in2="background" />
    </filter>
    
    <linearGradient id="animation">
           <stop offset="0" stop-color="rgba(248, 222, 86, 0)"/>
           <stop offset="100%" stop-color="#65ae83"/>
        </linearGradient>
  </defs>
  <g filter="url(#floodFilter)">
    <rect width="100" height="200" fill="url(#animation)" rx="8">
     <animate attributeType="XML" attributeName="x" from="-100" to="100" dur="1s" repeatCount="indefinite"/>
    </rect>
  </g>
</svg>

内容的提问来源于stack exchange,提问作者Marty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:05:32