1、SVG
1.1 概述
SVG是一种用于描述图形的XML语法。由于结构是XML格式,使得它可以插入HTML文档,成为DOM的一部分,然后用JavaScript和CSS进行操作。
一个简单的SVG文件如下:
<svg xmlns="http://www.w3.org/2000/svg" vieBox="0 0 1000 1000" id="mySvg">
<rect x="100" y="200" width="800" height="600" stroke="black" stroke-width="25" fill="red"/>
</svg>
1.2 使用方法
要使用SVG有很多方法,最简单的就是直接将SVG代码嵌入到HTML中:
<body>
<svg xmlns="http://www.w3.org/2000/svg" vieBox="0 0 1000 1000" id="mySvg"> <rect x="100" y="200" width="800" height="600" stroke="black" stroke-width="25" fill="red"/>
</svg>
</body>
SVG代码也可以单独写在一个文件中,后缀是“.svg”,然后用在、、、等标签,以及CSS的background-image属性,将这个文件插入网页。
<img src="example.svg">
<object data="example.svg" type="image/svg+xml"></object>
<embed src="example.svg" type="image/svg+xml">
<iframe src="example.svg"></iframe>
1.3 基本图形
(1)矩形
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect x="10" y="20" rx="5" ry="5" width="200" height="100"
style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0);fill-opacity:0.1;opacity:0.5" />
</svg>
属性说明:
rect 元素的 width 和 height 属性可定义矩形的高度和宽度
style 属性用来定义 CSS 属性
fill 属性定义矩形的填充颜色(rgb 值、颜色名或者十六进制值)
fill-opacity属性定义填充颜色的透明度
stroke-width 属性定义矩形边框的宽度
stroke 属性定义矩形边框的颜色
stroke-opacity属性定义笔触颜色的透明度
opacity属性定义元素的透明度
rx和ry属性定义矩形圆角
下面的其他图形都支持style属性,而且可以单独作为属性添加。
(2)圆形
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<circle cx="100" cy="50" r="40" stroke="black"
stroke-width="2" fill="red"/>
</svg>
属性说明:
cx和cy属性定义圆点的x和y坐标,如果省略,则默认为(0,0)
r属性定义圆的半径
(3)椭圆
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<ellipse cx="300" cy="80" rx="100" ry="50"
style="fill:yellow;stroke:purple;stroke-width:2"/>
</svg>
属性说明:
cx和cy属性定义椭圆的中心的x和y坐标
rx定义水平半径
ry定义垂直半径
(4)直线
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<line x1="0" y1="0" x2="200" y2="200"
style="stroke:rgb(255,0,0);stroke-width:2"/>
</svg>
属性说明:
x1和y1表示起始点的x和y坐标
x2和y2表示结束点的x和y坐标
(5)多边形
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<polygon points="200,10 250,190 160,210"
style="fill:lime;stroke:purple;stroke-width:1"/>
</svg>
属性说明:
points属性定义多边形每个角的x和y坐标,x和y坐标之间用逗号隔开,每个坐标点之间用空格隔开
(6)曲线
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<polyline points="20,20 40,25 60,40 80,120 120,140 200,180"
style="fill:none;stroke:black;stroke-width:3" />
</svg>
points属性定义多边形每个角的x和y坐标,x和y坐标之间用逗号隔开,每个坐标点之间用空格隔开
(7)文本
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<text x="0" y="15" fill="red">I love SVG</text>
</svg>
(8)路径
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<path d="M150 0 L75 200 L225 200 Z" />
</svg>