解決.svg無法在Azure websites載入顯示的問題

解決.svg無法在Azure websites載入顯示的問題

SVG稱可縮放的向量圖形,它本身有兩種格式,一種是XML格式,簡單想,它就如同一般HTML tag一樣,在網頁的中它使用<svg></svg>標籤。

SVG的XML格式

以下是使用wiki上的範例程式碼,你只要使用<svg></svg>標籤,就能在網頁上畫面你想要的任何向量圖。

  <!DOCTYPE html>
  <html lang="en">
  <head>
   <meta charset="UTF-8">
   <title>Document</title>
  </head>
  <body>
   <svg xmlns="http://www.w3.org/2000/svg" version="1.1" 
      width="467" height="462">
     <!-- This is the red square: -->
     <rect x="80" y="60" width="250" height="250" rx="20" fill="red"
           stroke="black" stroke-width="2px" />
     <!-- This is the blue square: -->
     <rect x="140" y="120" width="250" height="250" rx="40" fill="blue"
           stroke="black" stroke-width="2px" fill-opacity="0.7" />
  </svg>
  </body>
  </html>  
 

.svg檔案

如果你的這張SVG是要在多個網頁共用,那麼你也可以把上述SVG的XML另存為一個.svg的檔案中,.svg只是慣用的副檔名,內容基本還是剛剛的XML格式內容。

Visual Studio Edit SVG File

從圖片上可以看到,Visual Studio在編輯.svg檔案上也非常方便(就只是XML),並且提供預覽功能。各位可以在w3.org svg sameple找到更多很cool的範例。例如w3.org裡的car.svg範例:

car svg sample

你可以按【Ctrl+F5】看一下Car動畫效果。

發行至Microsoft Azure website

修改一下html,同時使用<svg>與.svg檔案:

  <p>下圖使用<svg></p>
  <svg xmlns="http://www.w3.org/2000/svg" version="1.1" 
  width="467" height="462">
  <!-- This is the red square: -->
  <rect x="80" y="60" width="250" height="250" rx="20" fill="red"
       stroke="black" stroke-width="2px" />
  <!-- This is the blue square: -->
  <rect x="140" y="120" width="250" height="250" rx="40" fill="blue"
       stroke="black" stroke-width="2px" fill-opacity="0.7" />
  </svg>
  <p>下圖使用.svg</p>
  <img src="car.svg" alt="car svg sample">
 

將頁面與car.svg發行至Azure website測試:

.svg unable load from azure website

很明顯.svg檔案的載入有問題,開啟Dev Tool可以看到car.svg得到是HTTP 404錯誤。

staticContent段落設置

如果要讓Azure websites支援.svg檔案,我們必須修改根目錄下的Web.config,加入以下段落設置:

  <configuration>
     <system.webServer>
        <staticContent>
           <remove fileExtension=".svg"/>
           <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
        </staticContent>
     </system.webServer>
  </configuration>
 

重新設置mimeType後,重新發行後就能看到.svg檔案被正確載入並呈現了。

沒有留言:

張貼留言

感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。