2014-01-26 44 views
1

我想用源組的所有顏色的漸變填充矩形。我相信有一個過濾器,但我無法建立一個完成工作。Svg過濾器將組的顏色作爲填充顏色應用於其他組或元素

<svg width="100" height="100"> 
    <defs> 
     <filter id="f1"> 
      <feBlend in="SourceGraphic" in2="url(#line)"/> 
     </filter> 
    </defs> 
    <g id="line"> 
     <line x1="10" y1="10" x2="20" y2="20" stroke="red"/> 
     <line x1="20" y1="20" x2="30" y2="10" stroke="orange"/> 
     <line x1="30" y1="10" x2="40" y2="20" stroke="green"/> 
     <line x1="40" y1="20" x2="50" y2="10" stroke="blue"/> 
    </g> 
    <g id="rect" filter="url(#f1)"> 
     <rect x="10" y="30" width="40" height="40" stroke="black" stroke-width="2"/> 
    </g> 
</svg> 

目標是我的矩形從源頭行(紅色,橙色,綠色和藍色)的顏色從左到右填充。 corse的源代碼顏色並不總是一樣的:-)我已經嘗試過幾個版本的feBlend,feFlood和feColorMatrix,沒有任何運氣。

回答

0

你不能僅僅在過濾器中引用一個對象,你必須先使用feImage導入它 - 在Firefox上不支持這樣做,並且在IE上偶爾會出現大小不一的問題。你也應該把你的填充模式放入你的defs中。下面是在Safari/Chrome瀏覽器的一個更大的版本 - 增加feTile所以你可以看到一個小更清晰的效果:

<svg width="400px" height="400px"> 
    <defs> 

    <g id="line"> 
     <line x1="10" y1="10" x2="20" y2="20" stroke="red"/> 
     <line x1="20" y1="20" x2="30" y2="10" stroke="orange"/> 
     <line x1="30" y1="10" x2="40" y2="20" stroke="green"/> 
     <line x1="40" y1="20" x2="50" y2="10" stroke="blue"/> 
    </g> 
     <filter id="f1" x="0%" y="0%" height="100%" width="100%"> 
      <feImage xlink:href="#line" width="50" height="20" result="myPattern"/> 
      <feTile in="myPattern" result="tilePattern"/> 
      <feBlend mode="normal" in="tilePattern" in2="SourceGraphic"/> 
     </filter> 
    </defs> 

    <g id="rect" filter="url(#f1)"> 
     <rect x="10" y="30" width="300" height="300" stroke="black" stroke-width="2"/> 
    </g> 
</svg> 

現在,如果你真的想這些顏色轉換爲漸變,你就必須在JavaScript中執行此操作。理論上來說,有一種方法可以通過使用fillPaint和strokePaint在過濾器中完成,但這些僅在IE和Firefox中受支持。我也不完全確定你想要達到什麼效果,發佈你想要做的事情的圖像會有幫助。

+0

「做這個不支持Firefox和大小是IE偶爾靠不住」,這聽起來像一個淘汰的標準給我。我收到通過web服務的svg,所以我沒有好的選擇來操縱dom ...旁邊的JavaScript ... – KIC

0

我不清楚你究竟想達到什麼效果。這是你所追求的效果嗎?

http://jsfiddle.net/t9Bfb/

<svg width="100%" height="100%" viewBox="0 0 60 60"> 
    <defs> 
     <linearGradient id="f1"> 
      <stop offset="0.125" stop-color="red"/> 
      <stop offset="0.275" stop-color="orange"/> 
      <stop offset="0.625" stop-color="green"/> 
      <stop offset="0.875" stop-color="blue"/> 
     </linearGradient> 
    </defs> 
    <g id="rect" fill="url(#f1)"> 
     <rect x="10" y="30" width="40" height="40" stroke="black" stroke-width="2"/> 
    </g> 
    <g id="line"> 
     <line x1="10" y1="10" x2="20" y2="20" stroke="red"/> 
     <line x1="20" y1="20" x2="30" y2="10" stroke="orange"/> 
     <line x1="30" y1="10" x2="40" y2="20" stroke="green"/> 
     <line x1="40" y1="20" x2="50" y2="10" stroke="blue"/> 
    </g> 
</svg> 
+0

是的,興奮!因爲線條組的顏色可能會改變,所以我想要一個過濾器,所以我不必照顧每一種顏色。 – KIC

+0

我沒有看到使用過濾器來獲取所需內容的方法。恐怕您需要查看腳本解決方案。 –

+0

好,那麼我想把你的評論放到你的答案中,並接受它作爲正確答案......至少這應該是什麼樣子。 – KIC