一:SVG的概述
SVG 意为可缩放矢量图形(Scalable Vector Graphics)。
SVG 使用 XML 格式定义图像。
SVG 图像在放大或改变尺寸的情况下其图形质量不会有损失。
二、SVG的优势
SVG 图像可通过文本编辑器来创建和修改;
SVG 图像可被搜索、索引、脚本化或压缩;
SVG 是可伸缩的;
SVG 图像可在任何的分辨率下被高质量地打印;
SVG 可在图像质量不下降的情况下被放大;
三、SVG的使用
1.直接在body内添加svg标签,默认尺寸是300 x 150
<svg width="800" height="800" xmlns="http://www.w3.org/2000/svg" version="1.1"> </svg>
注意:1:width height 指的是svg 的宽度和高度
2:xmlns="http://www.w3.org/2000/svg" 引入命名空间, 是Version svg语法的标准
3:SVG 代码以 <svg> 元素开始,包括开启标签 <svg> 和关闭标签 </svg> 。这是根元素。
4:在<svg>标签中写SVG一些预定义的元素
- 矩形 <rect>
- 圆形 <circle>
- 椭圆 <ellipse>
- 线 <line>
- 折线 <polyline>
- 多边形 <polygon>
- 路径 <path>
(1)矩形:<rect>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect x="50" y="20" rx="20" ry="20" width="150" height="150"
style="fill:red;stroke:black;stroke-width:5;opacity:0.5"/>
</svg>
注意:样式可以通过行内样式style 也可以通过属性:属性值 属性值不带单位
x='矩形左上角位置' y='矩形右上角位置'
rx='圆角的x方位半径,默认为0' ry='圆角的y方位半径,默认为0'
width:宽度 height:高度 fill:内部填充颜色
stroke:给图形描边 (stroke:"red")
stroke-width:描边宽度
(2)直线 : <line>
<line x1="0" y1="0" x2="200" y2="200" style="stroke:red;stroke-width:2"/>
注意:
- x1 属性在 x 轴定义线条的开始
- y1 属性在 y 轴定义线条的开始
- x2 属性在 x 轴定义线条的结束
- y2 属性在 y 轴定义线条的结束
- stroke:给图形描边 (stroke:"red")
-
stroke-width:描边宽度
(3)折线 <polyline>
<polyline points="390,390,360,440,440,440,410,390" stroke="gray" stroke-width="2" fill="gray">
</polyline>
注意:
1.points="坐标点(不用分顺序) 多个坐标点之间用,隔开"
(4)圆形 <circle>
<circle cx="400" cy="400" r="200" fill="yellow" style="stroke:black;stroke-width:2">
</circle>
注意点:
cx,cy是圆心的坐标, 如果省略cx和cy,圆的中心会被设置为(0, 0)
r 是圆的半径
(5)椭圆 <ellipse>
<ellipse cx="300" cy="360" rx="60" ry="30" fill="white" stroke="black"></ellipse>
- CX属性定义的椭圆中心的x坐标
- CY属性定义的椭圆中心的y坐标
- RX属性定义的水平半径
- RY属性定义的垂直半径
2.可以把svg当成一个图片,可以给img添加src属性进行显示
<img src="./svg1.svg" alt="">
svg文件中:可以用 <a> 标签链接到一个 SVG 文件:
<a href="http://www.baidu.com">
<rect x="10" y="10" width="100" height="100" rx="10" ry="10" fill="gray"></rect>
<text x="40" y="60" font-size="10">click here</text>
</a>
效果:
点击跳转到a 标签中指定的 URL
四:SVG事件
通过<set>标签attributeName
<rect x="10" y="10" width="140" height="100" rx="5" ry="5" fill="blue">
<set attributeName="fill" from="blue" to="red" begin="mouseover" end="mouseout"></set>
</rect>
<text x="200" y="75" font-size="12" fill="blue">move here
<set attributeName="font-size" from="30" to="50" begin="mouseover" end="mouseout"></set>
<set attributeName="fill" from="blue" to="red" begin="mousedown" end="mouseup"></set>
</text>
效果图;
事件处理后:
五: svg与canvas的区别
canvas
canvas通过.png或者.jpg的格式进行保存
依赖于分辨率
不支持事件处理
最适合图像比较密集的游戏
svg
可以支持事件处理
不依赖于分辨率
最适合使用于大型的渲染区域的应用(地图)
复杂度比较高的图形 渲染的时候就比较慢(通过操作dom元素应用都比较慢)
不适合做游戏应用