Translate

2020年12月11日 星期五

SVG filter 令人困擾的 feImage

filter 中的 feImage 有個有趣的用法,可以把任何一個 SVG 中的物件當作圖檔處理,範例如下


第一張圖,feImage 接了一張外部的 jpg 圖檔,原來的圓形套用後,可以正常顯示疊合的效果<br>
<svg width="300" height="300" style="background-color:#ffa" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
  <filter id="a121101_f1">
    <feImage xlink:href="https://yiharng.github.io/bird.jpg" x="30" y="30" width="240" height="240" preserveAspectRatio="none" result="a121101_img1"></feImage>
    <feBlend in2="a121101_img1" in="SourceGraphic"></feBlend>
  </filter>
</defs>
<circle id="c1" cx="150" cy="150" r="100" filter="url(#a121101_f1)" fill="#0ff5"></circle>
</svg><br>
<br>
第二張圖, feImage 接了 defs 中定義的 path 三角形,在 chrome 和 safari 有秀出來,但是 feImage 設定的 width 及 height 沒有變形作用,而 firefox 無法顯示,<br>
<svg width="300" height="300" style="background-color:#ffa" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
  <filter id="a121101_f2">
    <feImage xlink:href="#a121101_p2" x="30" y="30" width="240" height="240" preserveAspectRatio="none" result="a121101_img2"></feImage>
    <feBlend in2="a121101_img2" in="SourceGraphic"></feBlend>
  </filter>
  <path id="a121101_p2" d="M0,150 L120,0 L240,150z" fill="#fa0"></path>
</defs>
<circle id="a121101_c2" cx="150" cy="150" r="100" filter="url(#a121101_f2)" fill="#0ff5"></circle>
</svg>
第一張圖,feImage 接了一張外部的 jpg 圖檔,原來的圓形套用後,可以正常顯示疊合的效果


第二張圖, feImage 接了 defs 中定義的 path 三角形,在 chrome 和 safari 有秀出來,但是 feImage 設定的 width 及 height 沒有變形作用,而 firefox 無法顯示,

那麼如果要以現成的圖放到 filter 使用有沒有什麼方法呢 ? 也許是我才疏學淺,找了很久似忽沒有現成的方法可以解決 firefox 的問題,也沒有其它引入圖形處理的方法,最後只有想到一個有點暴力的方式,利用之前用過的 inline SVG 來解決

由下面範例可以發現,本來的 240x150 的圖,在之前範例中並沒有被縮放成 240x240 , 而使用 data:image 的方式會被視為外部的圖檔,正常縮放為 240x240



<svg width="300" height="300" style="background-color:#ffa" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
  <filter id="a121102_f2">
    <feImage id="a121102_feimg" xlink:href="" x="30" y="30" width="240" height="240" preserveAspectRatio="none" result="a121102_img2"></feImage>
    <feBlend in2="a121102_img2" in="SourceGraphic"></feBlend>
  </filter>
</defs>
<circle id="a121102_c2" cx="150" cy="150" r="100" filter="url(#a121102_f2)" fill="#0ff5"></circle>
</svg>
<script>
$(function()
{
  let hh='<svg width="240" height="150" xmlns="http://www.w3.org/2000/svg">'
        +'<path d="M0,150 L120,0 L240,150z" fill="#fa0"></path></svg>';
  $("#a121102_feimg").attr("xlink:href"
    ,"data:image/svg+xml;charset=UTF-8,"+escape(hh));
})
</script>  

沒有留言:

張貼留言