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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM