Translate

2020年8月21日 星期五

SVG 基礎

早期在 IE6 的時代接觸到 javascript ,覺得這個東西相當有趣,還可以搭配 java applet 做出很多效果,後來還用 java applet 開發電子地圖EGM 並利用 javascript 去控制 applet 中的物件;在那個時期想要在網頁上畫向量的點線面是相當麻煩的一件事,我當時的做法是利用 applet 來畫,後來得知還有另一個方式是 VML ,只是在當時只有 IE 支援,而且我要開發地圖需要更快的速度以及要解決網路傳輸的問題,最後還是選擇 applet ,當時甚至規劃了一整套 javascript 的 function ,可以在 applet 上畫向量,而如今瀏覽器已經不再支援 applet ,javascript 的功能也強大到足以取代 applet 和 flash

現在要在瀏覽器畫向量圖完全沒有問題,使用 SVG 不但功能強大,而且很多繪圖軟體都支援,和 javascript 的整合也相當完整,那麼就在這裡先整理 SVG 的基礎架構吧 !

svg 命名空間宣告,(如果沒有宣告,可能會看不到圖)
           xmlns="http://www.w3.org/2000/svg" 
           xmlns:xlink="http://www.w3.org/1999/xlink" 
           xmlns:ev="http://www.w3.org/2001/xml-events"

svg      - 最外層 svg 宣告,參數:
           width   - 寬
           height  - 高
           viewbox - 左上x 左上y 寬 高 (重新定義座標系)
           preserveAspectRatio - 預設為 xMidYMid meet
               參數組合為 xMin,xMid,xMax (注意 x 是小寫)
               加上 YMin,YMid,YMax (注意 Y 是大寫)
               加上空格後接 meet (填滿) 或 slice (裁切)  
               設為 none 會變形縮放

g        - group,相當於 layer
line     - 畫線,參數 x1,y1 畫到 x2,y2
polyline - 畫線,參數 points="x1,y1 x2,y2 x3,y3 ..."
polygon  - 畫面,參數 points="x1,y1 x2,y2 x3,y3 ..."
rect     - 矩形,參數 x,y,width,height,rx,ry (rx,ry 為圓角)
circle   - 畫圓,參數 cx,cy,r(半徑)
ellipse  - 橢圓,參數 cx,cy,rx,ry
text     - 文字,參數 x,y
image    - 圖片,參數 href="網址" x,y,width,height,preserveAspectRatio

共用參數 : **(CSS 有設定時以 CSS 設定優先)**
  stroke : "#顏色" , 線段顏色
  stroke-width : n , 線段寬度
  fill : "#顏色" , 填充顏色
  fill-rule : nonzero 或 evenodd

關於 preserveAspectRatio 的值同 svg 參數,可以參考 這裡 ,底下的範例設為 none 這樣圖片才會跟著設定的大小變形

範例:


<style>
.a08211_c1
{
  stroke:#000;
  stroke-width:3;
  fill:none;
}
.a08211_c2
{
  stroke:#f00;
  fill:#ff0;
  stroke-width:3;
  font-size:54px;
}
</style>

<svg width="300" height="300" viewBox="0 0 350 300" preserveAspectRatio="xMidYMid meet" style="background-color:#ddddff">
  <g id="a08211_layer1" class="a08211_c1">
    <line x1="0" y1="0" x2="100" y2="20"></line>
    <line x1="0" y1="10" x2="100" y2="30" stroke="#ff0000"></line>
    <line x1="0" y1="20" x2="100" y2="40" stroke="#ff0000" style="stroke:#00ff00"></line> 
    <!-- 當 css 的 style 設定 stroke 後,本來的 stroke 設定就被蓋掉了 -->
    <polyline points="120,5 200,5 200,40 160,40"></polyline>
    <polygon points="120,65 200,65 200,100 160,100"></polygon>
  </g>
  <g id="a08211_layer2" class="a08211_c2">
    <rect x="10" y="60" width="60" height="40" rx="20" ry="10"></rect>
    <circle cx="40" cy="160" r="30"></circle>
    <ellipse cx="150" cy="160" rx="50" ry="30"></ellipse>
    <polyline points="220,5 300,5 300,40 260,40"></polyline>
    <polygon points="220,65 300,65 300,100 260,100"></polygon>
    <text x="210" y="180">123</text>
    <image href="https://yiharng.github.io/bird.jpg" x="0" y="200" width="300" height="100" preserveAspectRatio="none"></image>
  </g>
</svg>
123

沒有留言:

張貼留言