在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/