SVG Scalable Vector Graphics
SVG 是使用 XML 来描述二维图形和绘图程序的语言。
W3school SVG教程
1. SVG 形状
矩形 rect
圆形 circle
椭圆 ellipse
线 line
折线 polyline
多边形 polygon
路径 path
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<rect width="300" height="100"
style="fill:rgb(0,0,255);stroke-width:1;
stroke:rgb(0,0,0)"/>
</svg>
2. SVG 滤镜
SVG 滤镜用来向形状和文本添加特殊的效果。
在 SVG 中,可用的滤镜有:
feBlend
feColorMatrix
feComponentTransfer
feComposite
feConvolveMatrix
feDiffuseLighting
feDisplacementMap
feFlood
feGaussianBlur
feImage
feMerge
feMorphology
feOffset
feSpecularLighting
feTile
feTurbulence
feDistantLight
fePointLight
feSpotLight
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<defs>
<filter id="Gaussian_Blur">
<feGaussianBlur in="SourceGraphic" stdDeviation="3" />
</filter>
</defs>
<ellipse cx="200" cy="150" rx="70" ry="40"
style="fill:#ff0000;stroke:#000000;
stroke-width:2;filter:url(#Gaussian_Blur)"/>
</svg>
3. SVG 渐变
渐变是一种从一种颜色到另一种颜色的平滑过渡。另外,可以把多个颜色的过渡应用到同一个元素上。
在 SVG 中,有两种主要的渐变类型:
线性渐变 linearGradient 可用来定义 SVG 的线性渐变。
放射性渐变 radialGradient 用来定义放射性渐变。
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<defs>
<radialGradient id="grey_blue" cx="50%" cy="50%" r="50%"
fx="50%" fy="50%">
<stop offset="0%" style="stop-color:rgb(200,200,200);
stop-opacity:0"/>
<stop offset="100%" style="stop-color:rgb(0,0,255);
stop-opacity:1"/>
</radialGradient>
</defs>
<ellipse cx="230" cy="200" rx="110" ry="100"
style="fill:url(#grey_blue)"/>
</svg>
4. 通过js切换svg填充色
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>polygon svg</title>
</head>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
<body>
<div style="width:100px height:100px">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190">
<polygon points="100,10 40,180 190,60 10,60 160,180" style="stroke:purple;stroke-width:0;fill-rule:evenodd;" />
</svg>
</div>
<button onclick="changecolor('#00ff00');">change color green</button>
<button onclick="changecolor('#0000ff');">change color blue</button>
<script>
function changecolor(color) {
console.log("begin")
$('svg').each(function() {
console.log(this)
$(this).attr("fill", color);
})
console.log("finish")
}
</script>
</body>
</html>
5 svg工具
这里只推荐下Inkscape,因为它是开源工具,而且免费使用。当然,对于企业和大款,推荐AI(Adobe Illustrator)或者其它收费软件 ,收费就有收费的道理。
使用Inkscape时,第一步建议设置画布大小,在文件-文档属性对话框中设置。
6 svg优化
使用工具开发出来的svg,里面对显示没有用的信息比较多,文本比较大。使用svgo,可以有效地去除这里面没有用的信息。
svgo下载安装,(下载安装到全局,Nodejs已经安装)
$npm install -g svgo
使用svgo优化
$svgo -i input.svg -o output.svg