1.问题描述:在使用linearGradient和filter给svg的path添加渐变色和阴影时,导致个别路径不显示
使用场景如下:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="svg" id="svg" ref="svg" :style="svgBgstyle">
<defs>
<linearGradient id="gradient2">
<stop offset="0%" stop-color="#10a5ff" />
<stop offset="50%" stop-color="#03c6fd" />
<stop offset="95%" stop-color="#11ffe4" />
</linearGradient>
<!-- 高斯模糊阴影,必须加filterUnits:否则有的路径不显示-->
<filter id="shadow2" >
<feGaussianBlur in="SourceGraphic" stdDeviation="6"/>
<feBlend in="SourceGraphic" mode="normal" />
</filter>
</defs>
<!-- 最优疏散路径 -->
<path v-for="(item, index) in pathList" class="firstPath" stroke-linecap="round" :key="'path' + index" :id="'path'+index" :d="item.path"></path>
</svg>
样式:
.firstPath {
cursor: pointer;
fill:none;
stroke-width:4;
stroke-dasharray: 60 60;
stroke-dashoffset: 0;
// stroke:#00cc66;
// 引用线性渐变和阴影效果
stroke:url(#gradient2);
filter:url(#shadow2);
animation: dash 3s linear infinite;
}
2.解决办法
(1)关键字objectBoundingBox这玩意儿,在元素没有宽度或者高度的时候,会失去作用,linearGradient渐变又依赖这个属性,所以失效了。解决方案很简单,为linearGradient加上属性gradientUnits="userSpaceOnUse"。gradientUnits是用于规定元素的坐标系统的,有两个属性userSpaceOnUse和objectBoundingBox,后者是默认的。
阴影效果应该是同样的原因:
加上属性:filterUnits="userSpaceOnUse"
如下:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="svg" id="svg" ref="svg" :style="svgBgstyle">
<!-- 线性渐变色,必须要加gradientUnits,否则有的路径不显示 -->
<defs>
<linearGradient id="gradient2" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#10a5ff" />
<stop offset="50%" stop-color="#03c6fd" />
<stop offset="95%" stop-color="#11ffe4" />
</linearGradient>
<!-- 高斯模糊阴影,必须加filterUnits:否则有的路径不显示-->
<filter id="shadow2" filterUnits="userSpaceOnUse">
<feGaussianBlur in="SourceGraphic" stdDeviation="6"/>
<feBlend in="SourceGraphic" mode="normal" />
</filter>
</defs>
<!-- 最优疏散路径 -->
<path v-for="(item, index) in pathList" class="firstPath" stroke-linecap="round" :key="'path' + index" :id="'path'+index" :d="item.path"></path>
</svg>