SVG:linearGradient渐变在直线上失效的问题解决方案

SVG开发里有个较为少见的问题。

对x1=x2或者y1=y2的直线(line以及path),比如:

<path d="M200,10 200,100" stroke="url(#orange_red)"/>

 

如果,stroke里使用的是渐变效果,那么,在各种浏览器上都会出现同一个BUG,这条线消失了。

原因不好排查,但是道理很简单,参考:

www.w3.org

Keyword objectBoundingBox should not be used when the geometry of the 
applicable element has no width or no height, such as the case of a horizontal 
or vertical line, even when the line has actual thickness when viewed due to 
having a non-zero stroke width since stroke width is ignored for bounding box 
calculations. When the geometry of the applicable element has no width or 
height and objectBoundingBox is specified, then the given effect (e.g., a 
gradient or a filter) will be ignored.

简而言之,就是说:

关键字objectBoundingBox这玩意儿,在元素没有宽度或者高度的时候,会失去作用。

 

linearGradient渐变又依赖这个属性,所以失效了。

解决方案很简单,为linearGradient加上属性gradientUnits="userSpaceOnUse"

gradientUnits是用于规定元素的坐标系统的,有两个属性userSpaceOnUse和objectBoundingBox,后者是默认的。

具体的说明参考:

gradientUnits MDN

 

posted @   荒土  阅读(2275)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2014-10-25 算法:poj1066 宝藏猎人问题。
点击右上角即可分享
微信分享提示