在SVG中使用樣式(四種方式,能夠聯想對照HTML樣式方法)css
內聯樣式, 直接在標籤裏設置style屬性html
<circle cx='20' cy='20' r='10' style='stroke: black; fill: blue;'/>
內部樣式表,能夠同時爲多個元素設置樣式 demogit
<svg width="200px" height="200px" viewBox="0 0 200 200"> <defs> <style type="text/css"><![CDATA[ circle { fill: #ffc; stroke: blue; stroke-width: 2; stroke-dasharray: 5 3 } ]]></style> </defs> <circle cx="20" cy="20" r="10"/> <circle cx="20" cy="60" r="10" style="fill: #cfc"/> </svg>
這裏使用了<![CDATA[...]]>
塊包裹<style>元素
內的CSS代碼(在XML文檔中的全部文本都會被解析器解析,只有在CDATA部件以內的文本會被解析器忽略)github
外部樣式表,將樣式寫在一個外部文件中,供一個或多個SVG文檔使用svg
<!-- ext_style.css --> * { fill: none; stroke: black; } rect { stroke-dasharray: 7 3;} .thick { stroke-width: 5; }
<?xml-stylesheet href="ext_style.css" type="text/css"?> ... <rect x="10" y="20" width="40" height="30"/> <polygon class="thick" points="60 50, 60 80, 90 80"/> ...
表現屬性,SVG容許咱們將style裏面的聲明直接當作SVG元素的屬性使用。如下兩段代碼效果是相同的。學習
<!-- 內聯樣式 --> <circle cx="10" cy="10" r="5" style="fill: red; stroke: black; stroke-width: 2;"/>
<!-- 表現屬性 --> <circle cx="10" cy="10" r="5" fill="red"; stroke="black"; stroke-width="2"/>
表現屬性是全部樣式中優先級最低的,但會覆蓋繼承的樣式。
<g>元素
<title>
和<desc>
。併爲子元素提供一些註解,使得文檔結構更爲清晰。在<g>
標籤中定義的樣式,會應用到全部子元素上。<use>元素
<use>
元素,爲定義在<g>
元素內的組合或任意獨立圖形元素提供了相似複製粘貼的能力。<defs>元素
<symbol>元素
<image>元素
能夠對照CSS3的Transform屬性學習理解。spa
變換 | 描述 |
---|---|
translate(x, y) | 按照指定的x和y值移動用戶座標系統。若是沒有指定y值,則假定爲0 demo |
scale(xFactor, yFactor) | 使用指定的xFactor和yFactor乘以全部的用戶座標系統。比例值能夠是小數或則負數 demo |
scale(factor) | 和scale(factor, factor)相同 |
rotate(angle, centerX, centerY) | 按照指定的angle旋轉用戶座標。旋轉中心由centerX和centerY指定 demo |
skewX(angle) | 根據指定的angle傾斜全部x座標。從視覺上講,這會讓垂直線出現角度 demo |
skewY(angle) | 根據指定的angle傾斜全部y座標。從視覺上講,這會讓水平線出現角度 |
matrix(a b c d e f) | 指定一個六個值組成的矩陣變換 |
Tip: 如何圍繞中心點縮放?
要圍繞某個點按照給定的比例縮放對象能夠這麼作:code
translate(-centerX * (factor - 1), -centerY * (factor - 1)) scale(factor)
還能夠將stroke-width的值也除以縮放係數,從而讓縮放後的輪廓保持一樣的寬度。orm
<!-- 縮放中心 --> <circle cx="50" cy="50" r="2" style="fill: black;"/> <!-- 未縮放的矩形 --> <g id="box" style="stroke: black; fill: none;"> <rect x="35" y="40" width="30" height="20"/> </g> <use xlink:href="#box" transform="translate(-50, -50) scale(2)" style="stroke-width: 0.5;"/> <use xlink:href="#box" transform="translate(-75, -75) scale(2.5)" style="stroke-width: 0.4;"/> <use xlink:href="#box" transform="translate(-100, -100) scale(3)" style="stroke-width: 0.33;"/>
原文連接: http://codesnote.com/svg_tutorial_part1/