2012-11-04 65 views
8

我使用svg繪製折線圖,​​並要求應用漸變。對於每一行,我使用一個路徑元素並將筆畫設置爲我的一個lineargradient元素。完美水平路徑的SVG漸變

這對一切都很好,但純粹的水平線 - 在這種情況下,我根本沒有獲得任何顏色。

我已示出該問題的小提琴:http://jsfiddle.net/b6EQT/

<svg> 
    <defs> 
     <linearGradient id="grad" x1="0%" x2="100%" y1="0%" y2="0%"> 
      <stop class="" offset="0%" style="stop-color: red;"></stop> 
      <stop class="" offset="33%" style="stop-color: yellow;"></stop> 
      <stop class="" offset="66%" style="stop-color: pink;"></stop> 
      <stop class="" offset="100%" style="stop-color: blue"></stop> 
     </linearGradient> 
    </defs> 
<-- Gradient not applied --> 
<path stroke="url(#grad)" d="M20,20L400,20" style="stroke-width: 10px;"></path> 

<-- Gradient applied since height of 1px --> 
<path stroke="url(#grad)" d="M20,40L400,41" style="stroke-width: 10px;"></path> 

<-- Gradient applied because of fake initial "move to" --> 
<path stroke="url(#grad)" d="M-1,-1,M20,60L400,60" style="stroke-width: 10px;"></path> 
</svg>​ 

純水平線(第一路徑)不出現,而第二個(在y中略有變化)一樣。

我嘗試了一些小技巧來開始 - 在開始時放置一個假M-1,-1,這似乎解決了IE和Chrome中的問題,但不是Firefox。這讓我覺得我在理解SVG漸變和路徑時錯過了一些東西。有沒有辦法讓這個工作?

回答

6

gradientUnits的默認值是objectBoundingBox。在specification text的最後一段中描述了您擁有的關鍵問題。如果你有一條水平線,爲什麼不用一個有填充的矩形而不是一條筆畫?或者使用userSpaceOnUse單位。

+2

這些圖表是自動生成的,所以不管它是一個完美的水平或不依賴於數據。 userSpaceOnUse單位完美工作,謝謝! – XwipeoutX

+0

@XwipeoutX如果您的路徑是從您的數據動態生成的,那麼選項可能會使路徑抖動一點點,以致它們不完全水平。這樣你可以保留objectBoundingBox,這可能更適合你,因爲停靠點的百分比屬於路徑本身 –

3

gradientUnits =「userSpaceOnUse」可以修復它。

Demo

<linearGradient id="grad" x1="0%" x2="100%" y1="0%" y2="0%" gradientUnits="userSpaceOnUse"> 
     <stop class="" offset="0%" style="stop-color: red;"></stop> 
     <stop class="" offset="33%" style="stop-color: yellow;"></stop> 
     <stop class="" offset="66%" style="stop-color: pink;"></stop> 
     <stop class="" offset="100%" style="stop-color: blue"></stop> 
</linearGradient> 

More detail answer