我有以下SVG文档:
<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 21 484" xmlns="http://www.w3.org/2000/svg">
<defs>
<filter id="dropShadow">
<feDropShadow dx="4" dy="0" stdDeviation="4"></feDropShadow>
</filter>
</defs>
<g id="Artboard" stroke-width="5" stroke="#FF0000" fill="#000000" stroke-linecap="round">
<path style="filter: url(#dropShadow)" d="M7.5,8.5 L7.5,471.5" id="path-1"></path>
</g>
</svg>
在 Firefox 中,当我打开 SVG 文档时,它只显示一条非常细(不是 5 宽)的垂直线。在 Chrome 中,它没有显示任何内容(在 codepen 中也没有,在这里:https://codepen.io/jwir3/pen/BJBqEK)。
我不太确定我在这里做错了什么,但这与过滤器有关,因为,如果我从
filter: url(#dropShadow)
定义中删除 path
,该行将按预期显示。
如果你的形状没有高度或宽度,你不能使用 objectBoundingBox 单位。
当适用元素的几何形状没有宽度或高度时,不应使用关键字 objectBoundingBox,例如水平或垂直线的情况,即使由于具有非零笔画宽度而在查看时该线具有实际粗细因为边界框计算忽略了笔划宽度。当适用元素的几何形状没有宽度或高度并且指定了 objectBoundingBox 时,将忽略给定的效果(例如,渐变或滤镜)。
filterUnits 的默认值是 objectBoundingBox 单位,因此您需要将其更改为 userSpaceOnUse 即
<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 21 484" xmlns="http://www.w3.org/2000/svg">
<title>Line Drop Shadow</title>
<description>A red line with 5px width thickness and round caps, having a drop-shadow. This highlights the regression documented in PURP-1017.</description>
<defs>
<filter id="dropShadow" filterUnits="userSpaceOnUse">
<feDropShadow dx="4" dy="0" stdDeviation="4"></feDropShadow>
</filter>
</defs>
<g id="Artboard" stroke-width="5" stroke="#FF0000" fill="#000000" stroke-linecap="round">
<path style="filter: url(#dropShadow)" d="M7.5,8.5 L7.5,471.5" id="path-1"></path>
</g>
</svg>
处理过滤器时,不同的浏览器以不同的方式处理
stroke
.Chrome
将 stroke 视为具有零像素的值,因此不将其包含在过滤器区域中。path
替换为stroke-width="5"
,一个宽度为5px的矩形,没有stroke
(stroke="none"
)
此外,过滤区域的默认值是:
x = "- 10%"
、y = "-10%"
、width = "120%"
、height = "120%"
- 大的模糊尺寸通常会被截断。
filterUnits = "objectBoundingBox"
因此值以百分比指定。
为了更容易计算
filter region
动作的大小,指定 filterUnits = "userSpaceOnUse"
的值,然后您可以指定 filter region
的所有尺寸(以像素为单位)。
<svg preserveAspectRatio="xMinYMin meet" width="100%" height="100%" viewBox="0 0 21 484" xmlns="http://www.w3.org/2000/svg" >
<defs>
<filter id="dropShadow" filterUnits = "userSpaceOnUse" x="4" y="0" width="12" height="472">
<feDropShadow dx="6" dy="4" stdDeviation="3"></feDropShadow>
</filter>
</defs>
<g id="Artboard" fill="#FF0000" filter="url(#dropShadow)" >
<!-- <path style="filter: url(#dropShadow)" d="M7.5,8.5 L7.5,471.5" id="path-1" stroke-width="5" ></path>-->
<rect x="5" y="5" width="5" stroke="none" height="463" />
</g>
</svg>
换成
userSpaceOnUse
在大多数情况下是正确答案,但有以下限制:
另一种(不太优雅)的解决方案是将过滤器应用于
<g>
并使用其中的隐藏节点为组提供正确的宽度或高度:
<svg xmlns="http://www.w3.org/2000/svg">
<defs>
<filter id="dropShadow" width="20">
<feDropShadow dx="4" dy="0" stdDeviation="4"></feDropShadow>
</filter>
</defs>
<g id="Artboard" style="filter: url(#dropShadow)">
<circle r="5" cx="0" cy="0" visibility="hidden"></circle>
<path d="M10,10 L10,100" stroke-width="5" stroke="#FF0000" fill="#000000" stroke-linecap="round"></path>
</g>
</svg>