除了Canvas,HTML5還提供另一種向量繪圖技術--SVG(Scalable Vector Graphics),透過XML標籤定義矩形、圓弧、路徑(Path)、多邊形(Polygon)等向量模型,並可加上濾鏡、變形等特效,就能在網頁顯示可縮放的向量圖案。而SVG的XML元素如同HTML元素能透過JavaScript動態改變屬性、樣式,甚至用CSS :hover選取器就能做出滑鼠移過變色效果,例如:

SVG與Canvas各有所長,適用場合不同,MSDN有篇詳細的分析可做為選擇評估的依據。

手上的專案決定採用SVG,卻遇到一個大問題: 公司還有一堆IE8甚至IE7餘孽未消,但IE9+才支援SVG啊!

Can I Use網站推薦SVG Polyfill -- SVG Web,遇到HTML5瀏覽器就直接顯示SVG,遇到"舊瀏覽器"(IE6/7/8,沒錯,就是在說你們! [氣]),則改用Flash解析SVG顯示圖案。

SVG Web用起來挺簡單。一開始先載入svg.js,在網頁裡用<script type="image/svg+xml">把<svg>文件包起來,svg.js就會視瀏覽器支援程度,直接顯示或是透過Flash呈現SVG圖案:

<!DOCTYPE html>
<html> 
  <head>
    <script src="js/svg.js" data-path="js" data-debug="true"></script>
  </head>
  <body>
      <script type="image/svg+xml">
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     height="800" width="800">
 <g transform="translate(200,200)" style="fill-opacity:1; fill:none;">
 <g style="fill: #ffffff; stroke:#000000; stroke-width:0.172">
  <path d="M-12 ... 省略 ... " >
 </g>
</svg>
  </body>
</html>

薑! 薑! 薑! 薑! 經典的SVG老虎在IE8現身了。按滑鼠右鍵可發現圖案部分其實是Flash物件:

經測試,SVG Web並沒有支援全部的SVG規格,例如漸層背景的顯示就有點問題。我們修改老虎SVG,用<defs><linearGradient>及<rect fille="url(...)">加上漸層背景矩形:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     height="800" width="800">
  <defs>
    <linearGradient id="linearGradient_0017">
      <stop id="stop_0018" stop-color="#003059" offset="0" />
      <stop id="stop_0019" stop-color="#0088ff" offset="0.95" />
      <stop id="stop_0020" stop-color="#ffffff" offset="1" />
    </linearGradient>
  </defs>     
  <rect id="rect_0002" x="0" y="0" width="600" height="600" 
   stroke="#aaa" stroke-width="2" fill="url(&quot;#linearGradient_0017&quot;)" />
 <g transform="translate(200,200)" style="fill-opacity:1; fill:none;">
 <g style="fill: #ffffff; stroke:#000000; stroke-width:0.172">

IE10/IE9及其他瀏覽器顯示正常,在IE8用Flash模擬時背景變成黑色。(左邊為模擬IE10模式的效果,右邊為IE8) 另外,遇到較複雜的SVG,Flash需花2-3秒才顯示結果,效能不如瀏覽器內建引擎,但SVG Web仍不失為可用的SVG跨"舊"瀏覽器解決方案。


Comments

# by 胡忠晞

我之前專案有用過 Raphaël http://raphaeljs.com/ 不知道你合不合用

Post a comment